| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| node-npmtest-s3fs/ | 100% | (153 / 153) | 100% | (126 / 126) | 100% | (28 / 28) | 100% | (153 / 153) | |
| node-npmtest-s3fs/node_modules/s3fs/ | 100% | (2 / 2) | 100% | (0 / 0) | 100% | (1 / 1) | 100% | (2 / 2) | |
| node-npmtest-s3fs/node_modules/s3fs/lib/ | 15.09% | (80 / 530) | 0% | (0 / 212) | 3.33% | (6 / 180) | 15.09% | (80 / 530) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/aws-sdk/lib/ | 22.49% | (388 / 1725) | 9.62% | (101 / 1050) | 18.37% | (61 / 332) | 23.94% | (380 / 1587) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/aws-sdk/lib/cloudfront/ | 20% | (12 / 60) | 0% | (0 / 30) | 0% | (0 / 13) | 20% | (12 / 60) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/aws-sdk/lib/credentials/ | 20.9% | (74 / 354) | 14.42% | (30 / 208) | 17.14% | (12 / 70) | 22.36% | (72 / 322) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/aws-sdk/lib/dynamodb/ | 10.37% | (31 / 299) | 0% | (0 / 144) | 0% | (0 / 39) | 10.88% | (31 / 285) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/aws-sdk/lib/http/ | 9.88% | (8 / 81) | 2.38% | (1 / 42) | 0% | (0 / 11) | 10.81% | (8 / 74) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/aws-sdk/lib/json/ | 20.22% | (18 / 89) | 0% | (0 / 45) | 0% | (0 / 20) | 23.38% | (18 / 77) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/aws-sdk/lib/model/ | 15.81% | (49 / 310) | 0% | (0 / 183) | 0% | (0 / 54) | 16.9% | (49 / 290) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/aws-sdk/lib/protocol/ | 15.24% | (41 / 269) | 0% | (0 / 149) | 0% | (0 / 32) | 15.89% | (41 / 258) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/aws-sdk/lib/query/ | 16.98% | (9 / 53) | 0% | (0 / 36) | 0% | (0 / 10) | 17.65% | (9 / 51) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/aws-sdk/lib/s3/ | 2.34% | (5 / 214) | 0% | (0 / 111) | 0% | (0 / 26) | 2.5% | (5 / 200) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/aws-sdk/lib/services/ | 6.19% | (34 / 549) | 0% | (0 / 433) | 0% | (0 / 84) | 6.44% | (34 / 528) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/aws-sdk/lib/signers/ | 12.96% | (42 / 324) | 0% | (0 / 133) | 0% | (0 / 56) | 13.38% | (42 / 314) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/aws-sdk/lib/xml/ | 15.48% | (24 / 155) | 0% | (0 / 114) | 0% | (0 / 25) | 16.55% | (24 / 145) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/bluebird/js/release/ | 27.46% | (897 / 3266) | 6.45% | (85 / 1318) | 10.64% | (60 / 564) | 28.27% | (888 / 3141) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/extend/ | 12.5% | (5 / 40) | 0% | (0 / 47) | 0% | (0 / 3) | 12.5% | (5 / 40) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/jmespath/ | 10.64% | (98 / 921) | 0.47% | (2 / 422) | 1.2% | (1 / 83) | 10.64% | (98 / 921) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/lodash/ | 88.24% | (15 / 17) | 75% | (3 / 4) | 50% | (1 / 2) | 93.75% | (15 / 16) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/lodash/collection/ | 42.86% | (3 / 7) | 0% | (0 / 6) | 0% | (0 / 1) | 42.86% | (3 / 7) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/lodash/internal/ | 30.92% | (111 / 359) | 3.16% | (9 / 285) | 8.89% | (4 / 45) | 30.92% | (111 / 359) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/lodash/lang/ | 78.26% | (54 / 69) | 24.49% | (12 / 49) | 12.5% | (1 / 8) | 78.26% | (54 / 69) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/lodash/object/ | 40.54% | (15 / 37) | 6.98% | (3 / 43) | 0% | (0 / 3) | 40.54% | (15 / 37) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/lodash/string/ | 100% | (6 / 6) | 75% | (3 / 4) | 100% | (1 / 1) | 100% | (6 / 6) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/lodash/utility/ | 66.67% | (2 / 3) | 100% | (0 / 0) | 0% | (0 / 1) | 66.67% | (2 / 3) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/sax/lib/ | 10.64% | (81 / 761) | 1.8% | (8 / 445) | 9.62% | (5 / 52) | 10.8% | (81 / 750) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/xml2js/lib/ | 15.19% | (53 / 349) | 0.51% | (1 / 198) | 17.02% | (8 / 47) | 13.55% | (45 / 332) | |
| node-npmtest-s3fs/node_modules/s3fs/node_modules/xmlbuilder/lib/ | 26.95% | (269 / 998) | 0% | (0 / 595) | 22.56% | (37 / 164) | 25.55% | (245 / 959) |
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| example.js | 100% | (83 / 83) | 100% | (73 / 73) | 100% | (12 / 12) | 100% | (83 / 83) | |
| lib.npmtest_s3fs.js | 100% | (16 / 16) | 100% | (14 / 14) | 100% | (3 / 3) | 100% | (16 / 16) | |
| test.js | 100% | (54 / 54) | 100% | (39 / 39) | 100% | (13 / 13) | 100% | (54 / 54) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | 2 2 2 2 2 2 2 1 2 2 2 2 1 2 2 2 2 2 1 2 1 1 1 1 1 1 1 1 1 2 1 1 1 1 2 2 3 3 3 3 1 3 3 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 6 6 1 2 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | /*
example.js
quickstart example
instruction
1. save this script as example.js
2. run the shell command:
$ npm install npmtest-s3fs && PORT=8081 node example.js
3. play with the browser-demo on http://127.0.0.1:8081
*/
/* istanbul instrument in package npmtest_s3fs */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 96,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - pre-init
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
// init utility2_rollup
local = local.global.utility2_rollup || (local.modeJs === 'browser'
? local.global.utility2_npmtest_s3fs
: global.utility2_moduleExports);
// export local
local.global.local = local;
}());
switch (local.modeJs) {
// post-init
// run browser js-env code - post-init
/* istanbul ignore next */
case 'browser':
local.testRunBrowser = function (event) {
Eif (!event || (event &&
event.currentTarget &&
event.currentTarget.className &&
event.currentTarget.className.includes &&
event.currentTarget.className.includes('onreset'))) {
// reset output
Array.from(
document.querySelectorAll('body > .resettable')
).forEach(function (element) {
switch (element.tagName) {
case 'INPUT':
case 'TEXTAREA':
element.value = '';
break;
default:
element.textContent = '';
}
});
}
switch (event && event.currentTarget && event.currentTarget.id) {
case 'testRunButton1':
// show tests
Eif (document.querySelector('#testReportDiv1').style.display === 'none') {
document.querySelector('#testReportDiv1').style.display = 'block';
document.querySelector('#testRunButton1').textContent =
'hide internal test';
local.modeTest = true;
local.testRunDefault(local);
// hide tests
} else {
document.querySelector('#testReportDiv1').style.display = 'none';
document.querySelector('#testRunButton1').textContent = 'run internal test';
}
break;
// custom-case
default:
break;
}
Iif (document.querySelector('#inputTextareaEval1') && (!event || (event &&
event.currentTarget &&
event.currentTarget.className &&
event.currentTarget.className.includes &&
event.currentTarget.className.includes('oneval')))) {
// try to eval input-code
try {
/*jslint evil: true*/
eval(document.querySelector('#inputTextareaEval1').value);
} catch (errorCaught) {
console.error(errorCaught);
}
}
};
// log stderr and stdout to #outputTextareaStdout1
['error', 'log'].forEach(function (key) {
console[key + '_original'] = console[key];
console[key] = function () {
var element;
console[key + '_original'].apply(console, arguments);
element = document.querySelector('#outputTextareaStdout1');
Iif (!element) {
return;
}
// append text to #outputTextareaStdout1
element.value += Array.from(arguments).map(function (arg) {
return typeof arg === 'string'
? arg
: JSON.stringify(arg, null, 4);
}).join(' ') + '\n';
// scroll textarea to bottom
element.scrollTop = element.scrollHeight;
};
});
// init event-handling
['change', 'click', 'keyup'].forEach(function (event) {
Array.from(document.querySelectorAll('.on' + event)).forEach(function (element) {
element.addEventListener(event, local.testRunBrowser);
});
});
// run tests
local.testRunBrowser();
break;
// run node js-env code - post-init
/* istanbul ignore next */
case 'node':
// export local
module.exports = local;
// require modules
local.fs = require('fs');
local.http = require('http');
local.url = require('url');
// init assets
local.assetsDict = local.assetsDict || {};
/* jslint-ignore-begin */
local.assetsDict['/assets.index.template.html'] = '\
<!doctype html>\n\
<html lang="en">\n\
<head>\n\
<meta charset="UTF-8">\n\
<meta name="viewport" content="width=device-width, initial-scale=1">\n\
<title>{{env.npm_package_name}} (v{{env.npm_package_version}})</title>\n\
<style>\n\
/*csslint\n\
box-sizing: false,\n\
universal-selector: false\n\
*/\n\
* {\n\
box-sizing: border-box;\n\
}\n\
body {\n\
background: #dde;\n\
font-family: Arial, Helvetica, sans-serif;\n\
margin: 2rem;\n\
}\n\
body > * {\n\
margin-bottom: 1rem;\n\
}\n\
.utility2FooterDiv {\n\
margin-top: 20px;\n\
text-align: center;\n\
}\n\
</style>\n\
<style>\n\
/*csslint\n\
*/\n\
textarea {\n\
font-family: monospace;\n\
height: 10rem;\n\
width: 100%;\n\
}\n\
textarea[readonly] {\n\
background: #ddd;\n\
}\n\
</style>\n\
</head>\n\
<body>\n\
<!-- utility2-comment\n\
<div id="ajaxProgressDiv1" style="background: #d00; height: 2px; left: 0; margin: 0; padding: 0; position: fixed; top: 0; transition: background 0.5s, width 1.5s; width: 25%;"></div>\n\
utility2-comment -->\n\
<h1>\n\
<!-- utility2-comment\n\
<a\n\
{{#if env.npm_package_homepage}}\n\
href="{{env.npm_package_homepage}}"\n\
{{/if env.npm_package_homepage}}\n\
target="_blank"\n\
>\n\
utility2-comment -->\n\
{{env.npm_package_name}} (v{{env.npm_package_version}})\n\
<!-- utility2-comment\n\
</a>\n\
utility2-comment -->\n\
</h1>\n\
<h3>{{env.npm_package_description}}</h3>\n\
<!-- utility2-comment\n\
<h4><a download href="assets.app.js">download standalone app</a></h4>\n\
<button class="onclick onreset" id="testRunButton1">run internal test</button><br>\n\
<div id="testReportDiv1" style="display: none;"></div>\n\
utility2-comment -->\n\
\n\
\n\
\n\
<label>stderr and stdout</label>\n\
<textarea class="resettable" id="outputTextareaStdout1" readonly></textarea>\n\
<!-- utility2-comment\n\
{{#if isRollup}}\n\
<script src="assets.app.js"></script>\n\
{{#unless isRollup}}\n\
utility2-comment -->\n\
<script src="assets.utility2.rollup.js"></script>\n\
<script src="jsonp.utility2._stateInit?callback=window.utility2._stateInit"></script>\n\
<script src="assets.npmtest_s3fs.rollup.js"></script>\n\
<script src="assets.example.js"></script>\n\
<script src="assets.test.js"></script>\n\
<!-- utility2-comment\n\
{{/if isRollup}}\n\
utility2-comment -->\n\
<div class="utility2FooterDiv">\n\
[ this app was created with\n\
<a href="https://github.com/kaizhu256/node-utility2" target="_blank">utility2</a>\n\
]\n\
</div>\n\
</body>\n\
</html>\n\
';
/* jslint-ignore-end */
Iif (local.templateRender) {
local.assetsDict['/'] = local.templateRender(
local.assetsDict['/assets.index.template.html'],
{
env: local.objectSetDefault(local.env, {
npm_package_description: 'the greatest app in the world!',
npm_package_name: 'my-app',
npm_package_nameAlias: 'my_app',
npm_package_version: '0.0.1'
})
}
);
} else {
local.assetsDict['/'] = local.assetsDict['/assets.index.template.html']
.replace((/\{\{env\.(\w+?)\}\}/g), function (match0, match1) {
// jslint-hack
String(match0);
switch (match1) {
case 'npm_package_description':
return 'the greatest app in the world!';
case 'npm_package_name':
return 'my-app';
case 'npm_package_nameAlias':
return 'my_app';
case 'npm_package_version':
return '0.0.1';
}
});
}
// run the cli
Eif (local.global.utility2_rollup || module !== require.main) {
break;
}
local.assetsDict['/assets.example.js'] =
local.assetsDict['/assets.example.js'] ||
local.fs.readFileSync(__filename, 'utf8');
// bug-workaround - long $npm_package_buildCustomOrg
/* jslint-ignore-begin */
local.assetsDict['/assets.npmtest_s3fs.rollup.js'] =
local.assetsDict['/assets.npmtest_s3fs.rollup.js'] ||
local.fs.readFileSync(
local.npmtest_s3fs.__dirname + '/lib.npmtest_s3fs.js',
'utf8'
).replace((/^#!/), '//');
/* jslint-ignore-end */
local.assetsDict['/favicon.ico'] = local.assetsDict['/favicon.ico'] || '';
// if $npm_config_timeout_exit exists,
// then exit this process after $npm_config_timeout_exit ms
if (Number(process.env.npm_config_timeout_exit)) {
setTimeout(process.exit, Number(process.env.npm_config_timeout_exit));
}
// start server
if (local.global.utility2_serverHttp1) {
break;
}
process.env.PORT = process.env.PORT || '8081';
console.error('server starting on port ' + process.env.PORT);
local.http.createServer(function (request, response) {
request.urlParsed = local.url.parse(request.url);
if (local.assetsDict[request.urlParsed.pathname] !== undefined) {
response.end(local.assetsDict[request.urlParsed.pathname]);
return;
}
response.statusCode = 404;
response.end();
}).listen(process.env.PORT);
break;
}
}());
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 2 2 2 2 2 2 2 1 2 2 2 2 1 1 1 1 | /* istanbul instrument in package npmtest_s3fs */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 96,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - pre-init
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
// init utility2_rollup
local = local.global.utility2_rollup || local;
// init lib
local.local = local.npmtest_s3fs = local;
// init exports
if (local.modeJs === 'browser') {
local.global.utility2_npmtest_s3fs = local;
} else {
module.exports = local;
module.exports.__dirname = __dirname;
module.exports.module = module;
}
}());
}());
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | 2 2 2 2 2 2 2 1 2 2 1 1 1 1 2 2 2 2 1 1 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 1 2 2 1 2 2 1 2 2 1 1 1 1 1 | /* istanbul instrument in package npmtest_s3fs */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 96,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - pre-init
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
switch (local.modeJs) {
// re-init local from window.local
case 'browser':
local = local.global.utility2.objectSetDefault(
local.global.utility2_rollup || local.global.local,
local.global.utility2
);
break;
// re-init local from example.js
case 'node':
local = (local.global.utility2_rollup || require('utility2'))
.requireExampleJsFromReadme();
break;
}
// export local
local.global.local = local;
}());
// run shared js-env code - function
(function () {
return;
}());
switch (local.modeJs) {
// run browser js-env code - function
case 'browser':
break;
// run node js-env code - function
case 'node':
break;
}
// run shared js-env code - post-init
(function () {
return;
}());
switch (local.modeJs) {
// run browser js-env code - post-init
case 'browser':
local.testCase_browser_nullCase = local.testCase_browser_nullCase || function (
options,
onError
) {
/*
* this function will test browsers's null-case handling-behavior-behavior
*/
onError(null, options);
};
// run tests
local.nop(local.modeTest &&
document.querySelector('#testRunButton1') &&
document.querySelector('#testRunButton1').click());
break;
// run node js-env code - post-init
/* istanbul ignore next */
case 'node':
local.testCase_buildApidoc_default = local.testCase_buildApidoc_default || function (
options,
onError
) {
/*
* this function will test buildApidoc's default handling-behavior-behavior
*/
options = { modulePathList: module.paths };
local.buildApidoc(options, onError);
};
local.testCase_buildApp_default = local.testCase_buildApp_default || function (
options,
onError
) {
/*
* this function will test buildApp's default handling-behavior-behavior
*/
local.testCase_buildReadme_default(options, local.onErrorThrow);
local.testCase_buildLib_default(options, local.onErrorThrow);
local.testCase_buildTest_default(options, local.onErrorThrow);
local.testCase_buildCustomOrg_default(options, local.onErrorThrow);
options = [];
local.buildApp(options, onError);
};
local.testCase_buildCustomOrg_default = local.testCase_buildCustomOrg_default ||
function (options, onError) {
/*
* this function will test buildCustomOrg's default handling-behavior
*/
options = {};
local.buildCustomOrg(options, onError);
};
local.testCase_buildLib_default = local.testCase_buildLib_default || function (
options,
onError
) {
/*
* this function will test buildLib's default handling-behavior
*/
options = {};
local.buildLib(options, onError);
};
local.testCase_buildReadme_default = local.testCase_buildReadme_default || function (
options,
onError
) {
/*
* this function will test buildReadme's default handling-behavior-behavior
*/
options = {};
local.buildReadme(options, onError);
};
local.testCase_buildTest_default = local.testCase_buildTest_default || function (
options,
onError
) {
/*
* this function will test buildTest's default handling-behavior
*/
options = {};
local.buildTest(options, onError);
};
local.testCase_webpage_default = local.testCase_webpage_default || function (
options,
onError
) {
/*
* this function will test webpage's default handling-behavior
*/
options = { modeCoverageMerge: true, url: local.serverLocalHost + '?modeTest=1' };
local.browserTest(options, onError);
};
// run test-server
local.testRunServer(local);
break;
}
}());
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| index.js | 100% | (2 / 2) | 100% | (0 / 0) | 100% | (1 / 1) | 100% | (2 / 2) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 1 1 | 'use strict';
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 Riptide Software Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
(function (module, s3fs) {
module.exports = s3fs;
}(module, require('./lib/s3fs')));
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| Stats.js | 27.08% | (13 / 48) | 0% | (0 / 10) | 7.69% | (1 / 13) | 27.08% | (13 / 48) | |
| fsInterface.js | 80% | (8 / 10) | 100% | (0 / 0) | 40% | (2 / 5) | 80% | (8 / 10) | |
| s3WriteStream.js | 16% | (16 / 100) | 0% | (0 / 30) | 3.03% | (1 / 33) | 16% | (16 / 100) | |
| s3fs.js | 12.27% | (40 / 326) | 0% | (0 / 140) | 0.84% | (1 / 119) | 12.27% | (40 / 326) | |
| utils.js | 6.52% | (3 / 46) | 0% | (0 / 32) | 10% | (1 / 10) | 6.52% | (3 / 46) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 Riptide Software Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
(function (module) {
var directoryRegexp = /\/$/,
statsArgs = [
'dev', 'mode', 'nlink', 'uid', 'gid', 'rdev', 'blksize', 'ino', 'size', 'blocks', 'atim_msec', 'mtim_msec', 'ctim_msec', 'birthtim_msec', 'path'
];
/* jscs: disable requireCamelCaseOrUpperCaseIdentifiers */
/* eslint-disable camelcase */
function Stats(dev, mode, nlink, uid, gid, rdev, blksize, ino, size, blocks, atim_msec, mtim_msec, ctim_msec, birthtim_msec, path) {
/* jshint maxparams: 4 */
if (arguments.length === 1 && typeof arguments[0] === 'object') {
return Stats.create(arguments[0]);
}
if (!Stats.is(this)) {
return new Stats(dev, mode, nlink, uid, gid, rdev, blksize, ino, size, blocks, atim_msec, mtim_msec, ctim_msec,
birthtim_msec, path);
}
var entry = path;
this.getEntry = function () {
return entry;
};
/* ID of device containing file */
this.dev = dev;
/* inode number */
this.mode = mode;
/* protection */
this.nlink = nlink;
/* number of hard links */
this.uid = uid;
/* user ID of owner */
this.gid = gid;
/* group ID of owner */
this.rdev = rdev;
/* device ID (if special file) */
this.blksize = blksize;
/* total size, in bytes */
this.ino = ino;
/* blocksize for file system I/O */
this.size = size;
/* number of 512B blocks allocated */
this.blocks = blocks;
/* time of last access */
this.atime = new Date(atim_msec);
/* time of last modification */
this.mtime = new Date(mtim_msec);
/* time of last status change */
this.ctime = new Date(ctim_msec);
this.birthtime = new Date(birthtim_msec);
}
/* eslint-enable camelcase */
/* jscs: enable requireCamelCaseOrUpperCaseIdentifiers */
Stats.is = function (object) {
return object instanceof Stats;
};
Stats.create = function (object) {
if (!object || typeof object !== 'object') {
throw new Error('object is required to create a Stats');
}
var args = [];
statsArgs.forEach(function (arg) {
args.push(object[arg]);
});
return Stats.apply(this, args);
};
Stats.prototype.isDirectory = function () {
return directoryRegexp.test(this.getEntry());
};
Stats.prototype.isFile = function () {
return !directoryRegexp.test(this.getEntry());
};
Stats.prototype.isBlockDevice = function () {
return false;
};
Stats.prototype.isCharacterDevice = function () {
return false;
};
Stats.prototype.isSymbolicLink = function () {
return false;
};
Stats.prototype.isFIFO = function () {
return false;
};
Stats.prototype.isSocket = function () {
return false;
};
module.exports = Stats;
}(module));
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 1 1 1 1 1 14 1 1 | 'use strict';
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 Riptide Software Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
(function (module, util) {
function notImplemented(method) {
throw new Error(util.format('function %s not implemented', method));
}
function FsInterface() {
}
var proto = {},
interfaces = ['stat', 'mkdir', 'readdir', 'realpath', 'rmdir', 'readFile', 'writeFile', 'appendFile', 'createReadStream', 'createWriteStream', 'unlink',
'exists', 'stat', 'lstat'];
interfaces.forEach(function (method) {
proto[method] = function () {
notImplemented(method);
};
});
FsInterface.prototype = proto;
module.exports = FsInterface;
}(module, require('util')));
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 Riptide Software Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
(function (module, Writable, util, extend, Promise) {
var defaultOptions = {},
maxParts = 1000,
partBufferSize = 5242880;
function MultiPartManager(client, bucket, key, options) {
this.client = client;
this.bucket = bucket;
this.key = key;
this.parts = [];
this.partNumber = 0;
this.currentBuffer = new Buffer(0);
this.bytesWritten = 0;
this.options = options || {};
}
MultiPartManager.prototype.addChunk = function (chunk) {
this.currentBuffer = Buffer.concat([this.currentBuffer, chunk]);
if (this.currentBuffer.length >= partBufferSize) {
var promise = this.addPart(this.currentBuffer);
this.parts.push(promise);
this.currentBuffer = new Buffer(0);
}
};
MultiPartManager.prototype.flush = function () {
if (this.currentBuffer.length) {
var promise = this.addPart(this.currentBuffer);
this.parts.push(promise);
this.currentBuffer = new Buffer(0);
}
};
MultiPartManager.prototype.addPart = function (buffer) {
var self = this,
partNumber = ++this.partNumber,
error;
if (partNumber > maxParts) {
error = util.format('Unable to create partNumber:%d. The max partNumber is %d', partNumber, maxParts);
return this.abort().then(function () {
return Promise.reject(error);
}, function () {
// TODO: combine reason with this error
return Promise.reject(error);
});
}
return this.uploadId().then(function (uploadId) {
return new Promise(function (resolve, reject) {
self.client.uploadPart({
Bucket: self.bucket,
Key: self.key,
Body: buffer,
UploadId: uploadId,
PartNumber: partNumber
}, function (err, result) {
if (err) {
return self.abort().then(function () {
reject(err);
}, function () {
//TODO: combine the multipart upload error with the abort error
reject(err);
});
}
result.PartNumber = partNumber;
self.bytesWritten += buffer.length;
resolve(result);
});
});
});
};
MultiPartManager.prototype.abort = function () {
var self = this;
return this.uploadId().then(function (uploadId) {
return new Promise(function (resolve, reject) {
self.client.abortMultipartUpload({
Bucket: self.bucket,
Key: self.key,
UploadId: uploadId
}, function (err) {
if (err) {
return reject(err);
}
resolve();
});
});
});
};
MultiPartManager.prototype.uploadId = function () {
var self = this;
/* jscs: disable disallowDanglingUnderscores */
if (!this._uploadIdPromise) {
this._uploadIdPromise = new Promise(function (resolve, reject) {
self.client.createMultipartUpload(extend({
Bucket: self.bucket,
Key: self.key
}, self.options), function (err, data) {
if (err) {
return reject(err);
}
resolve(data.UploadId);
});
});
}
return this._uploadIdPromise;
/* jscs: enable disallowDanglingUnderscores */
};
MultiPartManager.prototype.put = function () {
var self = this;
return new Promise(function (resolve, reject) {
self.client.putObject(extend(true, {
Bucket: self.bucket,
Key: self.key,
Body: self.currentBuffer
}, self.options), function (err, data) {
if (err) {
return reject(err);
}
self.bytesWritten += self.currentBuffer.length;
resolve(data);
});
});
};
MultiPartManager.prototype.complete = function () {
var self = this;
return this.partNumber ? this.uploadId().then(function (uploadId) {
self.flush();
return Promise.all(self.parts).then(function (parts) {
return new Promise(function (resolve, reject) {
self.client.completeMultipartUpload({
Bucket: self.bucket,
Key: self.key,
UploadId: uploadId,
MultipartUpload: {
Parts: parts
}
}, function (err, data) {
if (err) {
return reject(err);
}
resolve(data);
});
});
});
}) : this.put(); //if we did not reach the part limit of 5M just use putObject
};
function S3WriteStream(client, bucket, key, options) {
if (!(this instanceof S3WriteStream)) {
return new S3WriteStream(client, bucket, key, options);
}
this.multiPartManager = new MultiPartManager(client, bucket, key, options);
var streamOptions = extend(defaultOptions, options);
//initialize
Writable.call(this, streamOptions);
this.bytesWritten = 0;
}
util.inherits(S3WriteStream, Writable);
function execCb(cb) {
if (cb && typeof cb === 'function') {
cb();
}
}
S3WriteStream.prototype.write = function (chunk, enc, cb) {
this.multiPartManager.addChunk(chunk);
execCb(cb);
};
S3WriteStream.prototype.end = function (chunk, encoding, cb) {
var self = this;
if (chunk) {
this.multiPartManager.addChunk(chunk);
}
this.multiPartManager.complete().then(function () {
self.bytesWritten = self.multiPartManager.bytesWritten;
self.emit('finish');
execCb(cb);
}, function (reason) {
self.bytesWritten = self.multiPartManager.bytesWritten;
self.emit('error', reason);
execCb(cb);
});
};
module.exports = S3WriteStream;
}(module, require('stream').Writable, require('util'), require('extend'), require('bluebird')));
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | 'use strict';
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 Riptide Software Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
(function (module, fsInterface, util, Promise, AWS, s3Utils, extend, S3WriteStream, Stats) {
var directoryRegExp = /\/$/,
defaultCreateOptions = {};
function S3fs(bucket, options) {
if (!(this instanceof S3fs)) {
return new S3fs(bucket, options);
}
if (!bucket) {
throw new Error('bucket is required');
}
if (typeof bucket !== 'string') {
throw new Error('bucket must be a string');
}
var bucketParts = s3Utils.decomposePath(bucket);
this.s3 = options instanceof AWS.S3 ? options : new AWS.S3(options);
this.bucket = bucketParts[0];
this.path = bucketParts.slice(1).join('/');
if (this.path) {
this.path += '/';
}
}
function whiteSpace(item) {
return item;
}
util.inherits(S3fs, fsInterface);
/*
Begin FS Methods
*/
S3fs.prototype.createReadStream = function (name, options) {
return this.s3.getObject({
Bucket: this.bucket,
Key: s3Utils.toKey(s3Utils.joinPaths(this.path + s3Utils.toKey(name)))
}).createReadStream(options);
};
S3fs.prototype.createWriteStream = function (name, options) {
return new S3WriteStream(this.s3, this.bucket, s3Utils.toKey(s3Utils.joinPaths(this.path + s3Utils.toKey(name))), options);
};
S3fs.prototype.exists = function (name, callback) {
var self = this;
var promise = new Promise(function (resolve) {
var key = s3Utils.toKey(s3Utils.joinPaths(self.path + s3Utils.toKey(name)));
if (directoryRegExp.test(key)) {
return resolve(true); //TODO: Can we query S3 for this to see if the directory actually exists?
}
self.s3.headObject(
{
Bucket: self.bucket,
Key: key
},
function (err) {
if (err) {
return resolve(false);
}
resolve(true);
});
});
if (!callback) {
return promise;
}
promise.then(function (exists) {
callback(exists);
}, function () {
// Swallow the error (if one is hit), since exists doesn't send callback with an error in the normal FS interface.
callback(false);
});
};
/**
* [fs.mkdir(path[, mode], callback)](https://nodejs.org/api/fs.html#fs_fs_mkdir_path_mode_callback)
*
* Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback.
*
* @param path Relative path to be created
* @param callback Callback
* @returns {Promise}
*/
S3fs.prototype.mkdir = function mkdir(path, callback) {
//TODO: Add support for Mode, which by some form of magic would translate to S3 permissions. Not sure how we would maintain the same FS interface and convert it to S3 for permissions.
var promise = putObject(this.s3, this.bucket, s3Utils.toKey(s3Utils.joinPaths(this.path + s3Utils.toKey(path))) + '/');
if (!callback) {
return promise;
}
promise.then(function (data) {
callback(null, data);
}, function (reason) {
callback(reason);
});
};
/**
* [fs.mkdirp(path[, mode], callback)](https://github.com/RiptideCloud/s3fs#s3fsmkdirppath-cb)
*
* Asynchronous recursive mkdir(2). No arguments other than a possible exception are given to the completion callback.
*
* @param path Relative path to be created
* @param callback Callback
* @returns {Promise}
*/
S3fs.prototype.mkdirp = S3fs.prototype.mkdir;
S3fs.prototype.stat = function (path, callback) {
return getFileStats(this, path, callback);
};
S3fs.prototype.lstat = function (path, callback) {
return getFileStats(this, path, callback);
};
S3fs.prototype.readdir = function (name, callback) {
var prefix = s3Utils.toKey(s3Utils.joinPaths(this.path + s3Utils.toKey(name, this.bucket, this.path)));
// Make sure directories have a trailing slash.
if (prefix[prefix.length - 1] !== '/') {
prefix += '/';
}
var promise = listAllObjectsFiles(this.s3, this.bucket, prefix, '/');
if (!callback) {
return promise;
}
promise.then(function (files) {
callback(null, files);
}, function (reason) {
callback(reason);
});
};
S3fs.prototype.readFile = function (name, options, callback) {
var self = this;
var encoding;
var promise = new Promise(function(resolve) {
if (typeof options === 'function') {
callback = options;
options = undefined;
}
options = options || {};
// See: https://github.com/nodejs/node/blob/d6714ff1a48de5dcd9d3dfbb4b2e036efcd92b7c/lib/fs.js#L229-L235
options = handleReadWriteFileOptions(options);
encoding = options.encoding;
if (options.encoding) {
options = extend(true, {
ResponseContentEncoding: options.encoding
}, options);
delete options.encoding;
}
resolve(getObject(self.s3, self.bucket, s3Utils.toKey(s3Utils.joinPaths(self.path + s3Utils.toKey(name, self.bucket, self.path))), options));
});
if (!callback) {
return promise;
}
promise.then(function (data) {
// See: https://github.com/RiptideElements/s3fs/issues/37#issuecomment-135460856
if (encoding) {
return callback(null, data.Body.toString(encoding));
}
callback(null, data.Body); // Keep this in line with the FS interface and only return the contents.
}, function (reason) {
callback(reason);
});
};
S3fs.prototype.rmdir = function (path, callback) {
var promise = deleteObject(this.s3, this.bucket, s3Utils.toKey(s3Utils.joinPaths(this.path + s3Utils.toKey(path))) + '/');
if (!callback) {
return promise;
}
promise.then(function (data) {
callback(null, data);
}, function (reason) {
callback(reason);
});
};
S3fs.prototype.unlink = function (name, callback) {
var promise = deleteObject(this.s3, this.bucket, s3Utils.toKey(s3Utils.joinPaths(this.path + s3Utils.toKey(name, this.bucket, this.path))));
if (!callback) {
return promise;
}
promise.then(function (data) {
callback(null, data);
}, function (reason) {
callback(reason);
});
};
S3fs.prototype.writeFile = function (name, data, options, callback) {
var self = this;
var promise = new Promise(function(resolve) {
if (typeof options === 'function') {
callback = options;
options = undefined;
}
options = options || {};
// See: https://github.com/nodejs/node/blob/d6714ff1a48de5dcd9d3dfbb4b2e036efcd92b7c/lib/fs.js#L1120-L1126
options = handleReadWriteFileOptions(options);
if (options.encoding) {
options = extend(true, {
ContentEncoding: options.encoding
}, options);
delete options.encoding;
}
resolve(putObject(self.s3, self.bucket, s3Utils.toKey(s3Utils.joinPaths(self.path + s3Utils.toKey(name, self.bucket, self.path))), data, options));
});
if (!callback) {
return promise;
}
promise.then(function (res) {
callback(null, res);
}, function (reason) {
callback(reason);
});
};
/*
End FS Methods
*/
/*
Begin Custom Methods
*/
/**
* Provides a path by concatenating bucket with paths.
*
* @example
* ```js
* // Create an instance of S3FS which has a current working directory of `test-folder` within the S3 bucket `test-bucket`
* var fsImpl = new S3FS(options, 'test-bucket/test-folder');
*
* // Returns location to directory `test-bucket/test-folder/styles
* var fsImplStyles = fsImpl.getPath('styles');
* // Returns location to file `test-bucket/test-folder/styles/main.css
* var fsImplStyles = fsImpl.getPath('styles/main.css');
* // Returns location to file `test-bucket/test-folder
* var fsImplStyles = fsImpl.getPath();
* ```
*
* @param path `String`. _Optional_. The path to to directory or file
* @returns {String}
*/
S3fs.prototype.getPath = function (path) {
return s3Utils.joinPaths(this.bucket, s3Utils.joinPaths(this.path, path));
};
/**
* Provides a clone of the instance of S3FS which has relative access to the specified directory.
*
* @example
* ```js
* // Create an instance of S3FS which has a current working directory of `test-folder` within the S3 bucket `test-bucket`
* var fsImpl = new S3FS(options, 'test-bucket/test-folder');
* // Creates a copy (which uses the same instance of S3FS) which has a current working directory of `test-folder/styles`
* var fsImplStyles = fsImpl.clone('styles');
* ```
*
* @param path `String`. _Optional_. The relative path to extend the current working directory
* @returns {S3fs}
*/
S3fs.prototype.clone = function (path) {
return new S3fs(s3Utils.joinPaths(this.bucket, s3Utils.joinPaths(this.path, path)), this.s3);
};
/**
* Allows a file to be copied from one path to another path within the same bucket. Paths are relative to
* the bucket originally provided.
*
* @example
* ```js
* var fsImpl = new S3FS('test-bucket', options);
* fsImpl.copyFile('test-folder/test-file.txt', 'other-folder/test-file.txt').then(function() {
* // Object was successfully copied
* }, function(reason) {
* // Something went wrong
* });
* ```
*
* @param sourceFile `String`. **Required**. Relative path to the source file
* @param destinationFile `String`. **Required**. Relative path to the destination file
* @param options `Object`. _Optional_. The options to be used when copying the file. See [AWS SDK](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#copyObject-property)
* @param callback `Function`. _Optional_. Callback to be used, if not provided will return a Promise
* @returns {Promise|*} Returns a `Promise` if a callback is not provided
*/
S3fs.prototype.copyFile = function (sourceFile, destinationFile, options, callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
if (typeof options === 'function') {
callback = options;
options = undefined;
}
options = options || {};
self.s3.copyObject(extend(true, options, {
Bucket: self.bucket,
Key: s3Utils.toKey(s3Utils.joinPaths(self.path + s3Utils.toKey(destinationFile))),
CopySource: [self.bucket, s3Utils.toKey(s3Utils.joinPaths(self.path + s3Utils.toKey(sourceFile)))].join('/')
}), function (err, data) {
if (err) {
return reject(err);
}
return resolve(data);
});
});
if (!callback) {
return promise;
}
promise.then(function (data) {
callback(null, data);
}, function (reason) {
callback(reason);
});
};
/**
* Creates a new bucket on S3.
*
* @example
* ```js
* var fsImpl = new S3FS('test-bucket', options);
* fsImpl.create().then(function() {
* // Bucket was successfully created
* }, function(reason) {
* // Something went wrong
* });
* ```
*
* @param options `Object`. _Optional_. The options to be used when creating the bucket. See [AWS SDK](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#createBucket-property)
* @param callback `Function`. _Optional_. Callback to be used, if not provided will return a Promise
* @returns {Promise|*} Returns a `Promise` if a callback is not provided
*/
S3fs.prototype.create = function (options, callback) {
if (typeof options === 'function') {
callback = options;
options = undefined;
}
var self = this;
var params = extend(true, defaultCreateOptions, options, {Bucket: this.bucket});
var promise = new Promise(function (resolve, reject) {
self.s3.createBucket(params, function (err, data) {
if (err) {
return reject(err);
}
resolve(data);
});
});
if (!callback) {
return promise;
}
promise.then(function () {
callback();
}, function (reason) {
callback(reason);
});
};
/**
* Deletes a bucket on S3, can only be deleted when empty. If you need to delete one that isn't empty use
* `[destroy(cb)](#s3fs.destroy(cb))` instead.
*
* @example
* ```js
* var fsImpl = new S3FS('test-bucket', options);
* fsImpl.delete().then(function() {
* // Bucket was successfully deleted
* }, function(reason) {
* // Something went wrong
* });
* ```
*
* @param callback `Function`. _Optional_. Callback to be used, if not provided will return a Promise
* @returns {Promise|*} Returns a `Promise` if a callback is not provided
*/
S3fs.prototype.delete = function (callback) {
var self = this;
var promise = new Promise(function (resolve, reject) {
self.s3.deleteBucket({Bucket: self.bucket}, function (err, data) {
if (err) {
return reject(err);
}
resolve(data);
});
});
if (!callback) {
return promise;
}
promise.then(function () {
callback();
}, function (reason) {
callback(reason);
});
};
/**
* Retrieves the details about an object, but not the contents.
*
* @example
* ```js
* var fsImpl = new S3FS('test-bucket', options);
* fsImpl.headObject('test-file.txt').then(function(details) {
* // Details contains details such as the `ETag` about the object. See [AWS SDK](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#headObject-property) for details.
* }, function(reason) {
* // Something went wrong
* });
* ```
*
* @param path `String`. **Required**. Path to the object to retrieve the head for
* @param callback `Function`. _Optional_. Callback to be used, if not provided will return a Promise
* @returns {Promise|*} Returns a `Promise` if a callback is not provided
*/
S3fs.prototype.headObject = function (path, callback) {
//TODO: Convert the rest of the code to using this method for retrieving the head.
var self = this;
var promise = new Promise(function (resolve, reject) {
self.s3.headObject({
Bucket: self.bucket,
Key: s3Utils.toKey(s3Utils.joinPaths(self.path + s3Utils.toKey(path)))
}, function (err, data) {
if (err) {
return reject(err);
}
resolve(data);
});
});
if (!callback) {
return promise;
}
promise.then(function (data) {
callback(null, data);
}, function (reason) {
callback(reason);
});
};
/**
* Retrieves a list of all objects within the specific path. The result is similar to that of [headObject(path, cb](#s3fs.headObject(path, cb))
* expect that it contains an array of objects.
*
* @example
* ```js
* var fsImpl = new S3FS('test-bucket', options);
* fsImpl.listContents('/', '/').then(function(data) {
* // Data.Contents contains details such as the `ETag` about the object. See [AWS SDK](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#headObject-property) for details.
* }, function(reason) {
* // Something went wrong
* });
* ```
*
* @param path `String`. **Required**. The path to list all of the objects for
* @param marker `String`. **Required**. The key to start with when listing objects
* @param callback `Function`. _Optional_. Callback to be used, if not provided will return a Promise
* @returns {Promise|*} Returns a `Promise` if a callback is not provided
*/
S3fs.prototype.listContents = function (path, marker, callback) {
if (typeof marker === 'function') {
callback = marker;
marker = undefined;
}
var promise = listAllObjects(this.s3, this.bucket, s3Utils.toKey(s3Utils.joinPaths(this.path + s3Utils.toKey(path))) + '/', '/', marker);
if (!callback) {
return promise;
}
promise.then(function (data) {
callback(null, data);
}, function (reason) {
callback(reason);
});
};
/*
Begin Recursive Custom Methods
*/
/**
* Recursively copies a directory from the source path to the destination path.
*
* @example
* ```js
* var fsImpl = new S3FS('test-bucket', options);
* fsImpl.copyDir('test-folder', 'other-folder').then(function() {
* // Directory was successfully copied
* }, function(reason) {
* // Something went wrong
* });
* ```
*
* @param sourcePath `String`. **Required**. The source directory to be copied
* @param destinationPath `String`. **Required**. The destination directory to be copied to
* @param callback `Function`. _Optional_. Callback to be used, if not provided will return a Promise
* @returns {Promise|*} Returns a `Promise` if a callback is not provided
*/
S3fs.prototype.copyDir = function (sourcePath, destinationPath, callback) {
var self = this;
var promise = listAllObjectsFiles(this.s3, this.bucket, s3Utils.toKey(s3Utils.joinPaths(this.path + s3Utils.toKey(sourcePath))) + '/').then(function (files) {
var promises = [];
files.forEach(function (file) {
promises.push(self.copyFile([s3Utils.toKey(sourcePath), file].join('/'), [s3Utils.toKey(destinationPath), file].join('/')));
});
return Promise.all(promises).return();
});
if (!callback) {
return promise;
}
promise.then(function () {
callback();
}, function (reason) {
callback(reason);
});
};
/**
* Recursively deletes all files within the bucket and then deletes the bucket.
*
* @example
* ```js
* var fsImpl = new S3FS('test-bucket', options);
* fsImpl.destroy().then(function() {
* // Bucket was successfully destroyed
* }, function(reason) {
* // Something went wrong
* });
* ```
*
* @param callback `Function`. _Optional_. Callback to be used, if not provided will return a Promise
* @returns {Promise|*} Returns a `Promise` if a callback is not provided
*/
S3fs.prototype.destroy = function (callback) {
var self = this;
var promise = self.rmdirp()
.then(function () {
return listAllObjectsFiles(self.s3, self.bucket).then(function (objects) {
return Promise.all(objects.filter(function (object) {
//filter items
return !directoryRegExp.test(object);
}).map(function (object) {
//remove all the objects
return deleteObject(self.s3, self.bucket, object);
}).concat(objects.filter(function (object) {
return directoryRegExp.test(object);
}).map(function (object) {
//remove all folders
return deleteObject(self.s3, self.bucket, object);
})));
});
})
.then(function () {
return self.delete();
});
if (!callback) {
return promise;
}
promise.then(function () {
callback();
}, function (reason) {
callback(reason);
});
};
/**
* Adds/Updates a lifecycle on a bucket.
*
* @example
* ```js
* var fsImpl = new S3FS('test-bucket', options);
* // Remove the Cached contents in the `/cache` directory each day.
* fsImpl.putBucketLifecycle('expire cache', 'cache', 1).then(function() {
* // Bucket Lifecycle was successfully added/updated
* }, function(reason) {
* // Something went wrong
* });
* ```
*
* @param name `String`. **Required**. The name of the lifecycle. The value cannot be longer than 255 characters.
* @param prefix `String`. **Required**. Prefix identifying one or more objects to which the rule applies.
* @param days Indicates the lifetime, in days, of the objects that are subject to the rule. The value must be a non-zero positive integer.
* @param callback `Function`. _Optional_. Callback to be used, if not provided will return a Promise
* @returns {Promise|*} Returns a `Promise` if a callback is not provided
*/
S3fs.prototype.putBucketLifecycle = function (name, prefix, days, callback) {
var promise = putBucketLifecycle(this.s3, this.bucket, name, prefix, days);
if (!callback) {
return promise;
}
promise.then(function () {
callback();
}, function (reason) {
callback(reason);
});
};
/**
* Recursively reads a directory.
*
* @example
* ```js
* var fsImpl = new S3FS('test-bucket', options);
* fsImpl.readdirp('test-folder').then(function(files) {
* // Files contains a list of all of the files similar to [fs.readdir(path, callback)](http://nodejs.org/api/fs.html#fs_fs_readdir_path_callback) but with recursive contents
* }, function(reason) {
* // Something went wrong
* });
* ```
*
* @param path `String`. **Required**. The path to the directory to read from
* @param callback `Function`. _Optional_. Callback to be used, if not provided will return a Promise
* @returns {Promise|*} Returns a `Promise` if a callback is not provided
*/
S3fs.prototype.readdirp = function (path, callback) {
var prefix = s3Utils.toKey(s3Utils.joinPaths(this.path + s3Utils.toKey(path, this.bucket, this.path)));
if (prefix[prefix.length - 1] !== '/') {
prefix += '/'; // Make sure we have a trailing slash for the directory
}
var promise = listAllObjectsFiles(this.s3, this.bucket, prefix);
if (!callback) {
return promise;
}
promise.then(function (data) {
callback(null, data);
}, function (reason) {
callback(reason);
});
};
/**
* Recursively deletes a directory.
*
* @example
* ```js
* var fsImpl = new S3FS('test-bucket', options);
* fsImpl.rmdirp('test-folder').then(function() {
* // Directory has been recursively deleted
* }, function(reason) {
* // Something went wrong
* });
* ```
*
* @param path The path to the directory to delete
* @param callback `Function`. _Optional_. Callback to be used, if not provided will return a Promise
* @returns {Promise|*} Returns a `Promise` if a callback is not provided
*/
S3fs.prototype.rmdirp = function (path, callback) {
var self = this,
promise = listAllObjectsFiles(this.s3, this.bucket, path ? s3Utils.toKey(s3Utils.joinPaths(this.path + s3Utils.toKey(path))) + '/' : undefined).then(function (objects) {
return Promise.all(objects.filter(function (object) {
//filter items
return !directoryRegExp.test(object);
}).map(function (object) {
//remove all the items
return self.unlink((path ? s3Utils.toKey(path) + '/' : '') + object);
}).concat(objects.filter(function (object) {
return directoryRegExp.test(object);
}).map(function (object) {
//remove all folders
return self.rmdir((path ? s3Utils.toKey(path) + '/' : '') + object);
})));
});
if (!callback) {
return promise;
}
promise.then(function () {
callback();
}, function (reason) {
callback(reason);
});
};
/*
End Recursive Custom Methods
*/
/*
End Custom Methods
*/
/*
Begin Helper Methods
*/
function getFileStats(s3fs, path, callback) {
/* eslint-disable camelcase */
var promise = new Promise(function (resolve, reject) {
// S3 doesn't return information on directories and it automatically creates any that don't exist.
// So we can return semi-static information about the stats of a directory.
if (directoryRegExp.test(path)) {
var date = new Date(),
stats = new Stats({
dev: 0,
ino: 0,
mode: 0,
nlink: 1,
uid: 0,
gid: 0,
rdev: 0,
size: 0,
/* jscs: disable requireCamelCaseOrUpperCaseIdentifiers */
/* jshint camelcase: false */
atim_msec: date,
mtim_msec: date,
ctim_msec: date,
/* jshint camelcase: true */
/* jscs: enable requireCamelCaseOrUpperCaseIdentifiers */
path: path
});
return resolve(stats);
}
s3fs.s3.headObject({
Bucket: s3fs.bucket,
Key: s3Utils.toKey(s3Utils.joinPaths(s3fs.path + s3Utils.toKey(path, s3fs.bucket, s3fs.path)))
}, function (err, data) {
if (err) {
err.message = err.name;
return reject(err);
}
var statObj = new Stats({
dev: 0,
ino: 0,
mode: 0,
nlink: 0,
uid: 0,
gid: 0,
rdev: 0,
size: Number(data.ContentLength),
/* jscs: disable requireCamelCaseOrUpperCaseIdentifiers */
/* jshint camelcase: false */
atim_msec: data.LastModified,
mtim_msec: data.LastModified,
ctim_msec: data.LastModified,
/* jshint camelcase: true */
/* jscs: enable requireCamelCaseOrUpperCaseIdentifiers */
path: path
});
return resolve(statObj);
});
});
/* eslint-enable camelcase */
if (!callback) {
return promise;
}
promise.then(function (stats) {
callback(null, stats);
}, function (reason) {
callback(reason);
});
}
function contentToKey(content) {
return content.Key;
}
function contentPrefixesToPrefix(content) {
return content.Prefix;
}
function listAllObjects(s3, bucket, prefix, delimiter, marker) {
var objectPrefix = prefix === '/' ? undefined : prefix;
return new Promise(function (resolve, reject) {
s3.listObjects({
Bucket: bucket,
Delimiter: delimiter,
Marker: marker,
Prefix: objectPrefix
}, function (err, data) {
if (err) {
return reject(err);
}
var contentsList = data.Contents.map(function (item) {
if (objectPrefix && item && item.Key && item.Key.indexOf(objectPrefix) === 0) {
item.Key = item.Key.replace(objectPrefix, '');
}
return item;
}).filter(function (item) {
return item && item.Key;
});
if (data.IsTruncated) {
return listAllObjects(s3, bucket, prefix, delimiter, data.NextMarker).then(function (contents) {
resolve(contentsList.concat(contents));
}, function (reason) {
reject(reason);
});
}
return resolve(contentsList);
});
});
}
function listAllObjectsFiles(s3, bucket, prefix, delimiter, marker) {
var objectPrefix = prefix === '/' ? undefined : prefix;
return new Promise(function (resolve, reject) {
s3.listObjects({
Bucket: bucket,
Delimiter: delimiter,
Marker: marker,
Prefix: objectPrefix
}, function (err, data) {
if (err) {
return reject(err);
}
var fileList = data.Contents.map(contentToKey).concat(data.CommonPrefixes.map(contentPrefixesToPrefix)).map(function (item) {
if (objectPrefix && item.indexOf(objectPrefix) === 0) {
return item.replace(objectPrefix, '');
}
return item;
});
if (data.IsTruncated) {
return listAllObjectsFiles(s3, bucket, prefix, delimiter, data.NextMarker).then(function (files) {
resolve(fileList.concat(files));
}, function (reason) {
reject(reason);
});
}
resolve(fileList.filter(whiteSpace));
});
});
}
function getObject(s3, bucket, key, options) {
var s3Options = extend(typeof options === 'object' ? options : {}, {
Bucket: bucket,
Key: key
});
return new Promise(function (resolve, reject) {
s3.getObject(s3Options, function (err, data) {
if (err) {
return reject(err);
}
resolve(data);
});
});
}
function putObject(s3, bucket, key, body, options) {
var s3Options = extend(typeof options === 'object' ? options : {}, {
Bucket: bucket,
Key: key,
Body: body
});
return new Promise(function (resolve, reject) {
s3.putObject(s3Options, function (err, data) {
if (err) {
return reject(err);
}
resolve(data);
});
});
}
function deleteObject(s3, bucket, key) {
return new Promise(function (resolve, reject) {
s3.deleteObject({
Bucket: bucket,
Key: key
}, function (err, data) {
if (err) {
return reject(err);
}
resolve(data);
});
});
}
function putBucketLifecycle(s3, bucket, name, prefix, days) {
var options = {
Bucket: bucket,
LifecycleConfiguration: {
Rules: [
{
Prefix: prefix,
Status: 'Enabled',
Expiration: {
Days: days
},
ID: name
}
]
}
};
return new Promise(function (resolve, reject) {
s3.putBucketLifecycle(options, function (err, data) {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
}
function handleReadWriteFileOptions(options) {
if (typeof options === 'function' || !options) {
options = { encoding: null };
} else if (typeof options === 'string') {
options = { encoding: options };
} else if (!options) {
options = { encoding: null };
} else if (typeof options !== 'object') {
throw new TypeError('Bad arguments');
}
return options;
}
/*
End Helper Methods
*/
module.exports = S3fs;
}(module, require('./fsInterface'), require('util'), require('bluebird'), require('aws-sdk'), require('./utils'), require('extend'), require('./s3WriteStream'),
require('./Stats')));
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | 1 1 1 | 'use strict';
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2016 Riptide Software Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
(function (module) {
var splitDeviceRegExp = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
module.exports = {
isAbsolute: function (path) {
if (path[0] === '/') {
return true;
}
if (path[1] === ':' && path[2] === '\\') {
return true;
}
if (path.substring(0, 2) === '\\\\') {
// Microsoft Azure absolute path
return true;
}
return false;
},
normalizeArray: function (parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0,
i,
last;
for (i = parts.length - 1; i >= 0; i--) {
last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
},
normalizePath: function (path) {
var tailIndex = 3;
var result = splitDeviceRegExp.exec(path),
device = result[1] || '',
isAbsolute = this.isAbsolute(path),
tail = result[tailIndex],
trailingSlash = /[\\\/]$/.test(tail);
// Normalize the tail path
tail = this.normalizeArray(tail.split(/[\\\/]+/).filter(function (p) {
return !!p;
}), !isAbsolute).join('/');
if (tail && trailingSlash) {
tail += '/';
}
// Smash multiple slashes
return (device + (isAbsolute ? '\\' : '') + tail).replace(/[\\\/]+/g, '/');
},
decomposePath: function (path) {
var pathArray = [];
return path ? path.split('/').reduce(function (array, value) {
if (value) {
array.push(value);
}
return array;
}, pathArray) : pathArray;
},
toKey: function (fullPath, bucket, bucketPath) {
fullPath = fullPath || '';
var path = fullPath,
bucketKeyPath;
if (bucket) {
bucketKeyPath = this.joinPaths(bucket, bucketPath);
path = fullPath.replace(bucketKeyPath, '');
}
return this.normalizePath(this.decomposePath(path).join('/'));
},
joinPaths: function () {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function (array, path) {
return array.concat(this.decomposePath(path));
}.bind(this), []).join('/');
}
};
}(module));
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| api_loader.js | 54.65% | (47 / 86) | 31.58% | (12 / 38) | 57.14% | (8 / 14) | 57.5% | (46 / 80) | |
| aws.js | 76.67% | (23 / 30) | 50% | (3 / 6) | 63.64% | (7 / 11) | 79.31% | (23 / 29) | |
| config.js | 30.99% | (22 / 71) | 18.6% | (8 / 43) | 22.22% | (4 / 18) | 30.43% | (21 / 69) | |
| core.js | 95.65% | (22 / 23) | 100% | (0 / 0) | 0% | (0 / 1) | 95.45% | (21 / 22) | |
| credentials.js | 65.52% | (19 / 29) | 42.86% | (9 / 21) | 80% | (4 / 5) | 66.67% | (18 / 27) | |
| event_listeners.js | 22.08% | (53 / 240) | 0% | (0 / 134) | 17.39% | (8 / 46) | 23.25% | (53 / 228) | |
| http.js | 14.58% | (7 / 48) | 0% | (0 / 30) | 0% | (0 / 8) | 14.58% | (7 / 48) | |
| metadata_service.js | 15.79% | (6 / 38) | 0% | (0 / 8) | 0% | (0 / 10) | 18.18% | (6 / 33) | |
| param_validator.js | 1.64% | (2 / 122) | 0% | (0 / 126) | 0% | (0 / 15) | 1.89% | (2 / 106) | |
| region_config.js | 17.5% | (7 / 40) | 0% | (0 / 26) | 0% | (0 / 6) | 20% | (7 / 35) | |
| request.js | 15.23% | (30 / 197) | 0% | (0 / 93) | 2.56% | (1 / 39) | 16.13% | (30 / 186) | |
| resource_waiter.js | 11.11% | (8 / 72) | 0% | (0 / 44) | 7.14% | (1 / 14) | 12.12% | (8 / 66) | |
| response.js | 6.78% | (4 / 59) | 0% | (0 / 32) | 0% | (0 / 5) | 7.84% | (4 / 51) | |
| sequential_executor.js | 28.17% | (20 / 71) | 5.88% | (2 / 34) | 38.89% | (7 / 18) | 29.41% | (20 / 68) | |
| service.js | 11.22% | (22 / 196) | 7.35% | (10 / 136) | 5.71% | (2 / 35) | 11.96% | (22 / 184) | |
| services.js | 100% | (11 / 11) | 100% | (2 / 2) | 100% | (1 / 1) | 100% | (10 / 10) | |
| state_machine.js | 34.29% | (12 / 35) | 28.57% | (8 / 28) | 50% | (2 / 4) | 40.74% | (11 / 27) | |
| util.js | 20.45% | (73 / 357) | 18.88% | (47 / 249) | 19.51% | (16 / 82) | 22.33% | (71 / 318) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | 1 1 1 1 1 1 1 149 1 1 1 74 74 1 163 163 80 80 80 80 80 1 74 74 74 1 1 1 1 1 74 74 74 1 74 74 74 1 1 1 1 1 148 1 1 1 | var fs = require('fs');
var path = require('path');
var apiRoot = path.join(__dirname, '..', 'apis');
var serviceMap = null;
var serviceIdentifiers = [];
var serviceNames = [];
function buildServiceMap() {
if (serviceMap !== null) return;
// load info file for API metadata
serviceMap = require(path.join(apiRoot, 'metadata.json'));
var prefixMap = {};
Object.keys(serviceMap).forEach(function(identifier) {
serviceMap[identifier].prefix = serviceMap[identifier].prefix || identifier;
prefixMap[serviceMap[identifier].prefix] = identifier;
});
fs.readdirSync(apiRoot).forEach(function (file) {
var match = file.match(/^(.+?)-(\d+-\d+-\d+)\.(normal|min)\.json$/);
if (match) {
var id = prefixMap[match[1]], version = match[2];
Eif (serviceMap[id]) {
serviceMap[id].versions = serviceMap[id].versions || [];
Eif (serviceMap[id].versions.indexOf(version) < 0) {
serviceMap[id].versions.push(version);
}
}
}
});
Object.keys(serviceMap).forEach(function(identifier) {
serviceMap[identifier].versions = serviceMap[identifier].versions.sort();
serviceIdentifiers.push(identifier);
serviceNames.push(serviceMap[identifier].name);
});
}
function getServices() {
buildServiceMap();
return serviceIdentifiers;
}
function getServiceNames() {
buildServiceMap();
return serviceNames;
}
function serviceVersions(svc) {
buildServiceMap();
svc = serviceIdentifier(svc);
return serviceMap[svc] ? serviceMap[svc].versions : null;
}
function serviceName(svc) {
buildServiceMap();
svc = serviceIdentifier(svc);
return serviceMap[svc] ? serviceMap[svc].name : null;
}
function serviceFile(svc, version) {
buildServiceMap();
svc = serviceIdentifier(svc);
if (!serviceMap[svc]) return null;
var prefix = serviceMap[svc].prefix || svc;
var filePath;
['min', 'api', 'normal'].some(function(testSuffix) {
filePath = apiRoot + '/' + prefix.toLowerCase() + '-' + version + '.' +
testSuffix + '.json';
return fs.existsSync(filePath);
});
return filePath;
}
function paginatorsFile(svc, version) {
buildServiceMap();
svc = serviceIdentifier(svc);
if (!serviceMap[svc]) return null;
var prefix = serviceMap[svc].prefix || svc;
return apiRoot + '/' + prefix + '-' + version + '.paginators.json';
}
function waitersFile(svc, version) {
buildServiceMap();
svc = serviceIdentifier(svc);
if (!serviceMap[svc]) return null;
var prefix = serviceMap[svc].prefix || svc;
return apiRoot + '/' + prefix + '-' + version + '.waiters2.json';
}
function load(svc, version) {
buildServiceMap();
svc = serviceIdentifier(svc);
if (version === 'latest') version = null;
version = version || serviceMap[svc].versions[serviceMap[svc].versions.length - 1];
if (!serviceMap[svc]) return null;
var api = require(serviceFile(svc, version));
// Try to load paginators
if (fs.existsSync(paginatorsFile(svc, version))) {
var paginators = require(paginatorsFile(svc, version));
api.paginators = paginators.pagination;
}
// Try to load waiters
if (fs.existsSync(waitersFile(svc, version))) {
var waiters = require(waitersFile(svc, version));
api.waiters = waiters.waiters;
}
return api;
}
function serviceIdentifier(svc) {
return svc.toLowerCase();
}
module.exports = {
serviceVersions: serviceVersions,
serviceName: serviceName,
serviceIdentifier: serviceIdentifier,
serviceFile: serviceFile,
load: load
};
Object.defineProperty(module.exports, 'services', {
enumerable: true, get: getServices
});
Object.defineProperty(module.exports, 'serviceNames', {
enumerable: true, get: getServiceNames
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | var AWS = require('./core');
module.exports = AWS;
// Use default API loader function
AWS.apiLoader = require('./api_loader').load;
// Load the xml2js XML parser
AWS.XML.Parser = require('./xml/node_parser');
// Load Node HTTP client
require('./http/node');
// Load all service classes
require('./services');
// Load custom credential providers
require('./credentials/ec2_metadata_credentials');
require('./credentials/ecs_credentials');
require('./credentials/environment_credentials');
require('./credentials/file_system_credentials');
require('./credentials/shared_ini_file_credentials');
// Setup default chain providers
// If this changes, please update documentation for
// AWS.CredentialProviderChain.defaultProviders in
// credentials/credential_provider_chain.js
AWS.CredentialProviderChain.defaultProviders = [
function () { return new AWS.EnvironmentCredentials('AWS'); },
function () { return new AWS.EnvironmentCredentials('AMAZON'); },
function () { return new AWS.SharedIniFileCredentials(); },
function () {
if (AWS.ECSCredentials.prototype.getECSRelativeUri() !== undefined) {
return new AWS.ECSCredentials();
}
return new AWS.EC2MetadataCredentials();
}
];
// Update configuration keys
AWS.util.update(AWS.Config.prototype.keys, {
credentials: function () {
var credentials = null;
new AWS.CredentialProviderChain([
function () { return new AWS.EnvironmentCredentials('AWS'); },
function () { return new AWS.EnvironmentCredentials('AMAZON'); },
function () { return new AWS.SharedIniFileCredentials({ disableAssumeRole: true }); }
]).resolve(function(err, creds) {
Iif (!err) credentials = creds;
});
return credentials;
},
credentialProvider: function() {
return new AWS.CredentialProviderChain();
},
region: function() {
return process.env.AWS_REGION || process.env.AMAZON_REGION;
}
});
// Reset configuration
AWS.config = new AWS.Config();
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 | 1 1 1 1 2 2 2 50 1 1 1 1 50 50 4 50 3 47 2 2 1 | var AWS = require('./core');
require('./credentials');
require('./credentials/credential_provider_chain');
/**
* The main configuration class used by all service objects to set
* the region, credentials, and other options for requests.
*
* By default, credentials and region settings are left unconfigured.
* This should be configured by the application before using any
* AWS service APIs.
*
* In order to set global configuration options, properties should
* be assigned to the global {AWS.config} object.
*
* @see AWS.config
*
* @!group General Configuration Options
*
* @!attribute credentials
* @return [AWS.Credentials] the AWS credentials to sign requests with.
*
* @!attribute region
* @example Set the global region setting to us-west-2
* AWS.config.update({region: 'us-west-2'});
* @return [AWS.Credentials] The region to send service requests to.
* @see http://docs.amazonwebservices.com/general/latest/gr/rande.html
* A list of available endpoints for each AWS service
*
* @!attribute maxRetries
* @return [Integer] the maximum amount of retries to perform for a
* service request. By default this value is calculated by the specific
* service object that the request is being made to.
*
* @!attribute maxRedirects
* @return [Integer] the maximum amount of redirects to follow for a
* service request. Defaults to 10.
*
* @!attribute paramValidation
* @return [Boolean|map] whether input parameters should be validated against
* the operation description before sending the request. Defaults to true.
* Pass a map to enable any of the following specific validation features:
*
* * **min** [Boolean] — Validates that a value meets the min
* constraint. This is enabled by default when paramValidation is set
* to `true`.
* * **max** [Boolean] — Validates that a value meets the max
* constraint.
* * **pattern** [Boolean] — Validates that a string value matches a
* regular expression.
* * **enum** [Boolean] — Validates that a string value matches one
* of the allowable enum values.
*
* @!attribute computeChecksums
* @return [Boolean] whether to compute checksums for payload bodies when
* the service accepts it (currently supported in S3 only).
*
* @!attribute convertResponseTypes
* @return [Boolean] whether types are converted when parsing response data.
* Currently only supported for JSON based services. Turning this off may
* improve performance on large response payloads. Defaults to `true`.
*
* @!attribute correctClockSkew
* @return [Boolean] whether to apply a clock skew correction and retry
* requests that fail because of an skewed client clock. Defaults to
* `false`.
*
* @!attribute sslEnabled
* @return [Boolean] whether SSL is enabled for requests
*
* @!attribute s3ForcePathStyle
* @return [Boolean] whether to force path style URLs for S3 objects
*
* @!attribute s3BucketEndpoint
* @note Setting this configuration option requires an `endpoint` to be
* provided explicitly to the service constructor.
* @return [Boolean] whether the provided endpoint addresses an individual
* bucket (false if it addresses the root API endpoint).
*
* @!attribute s3DisableBodySigning
* @return [Boolean] whether to disable S3 body signing when using signature version `v4`.
* Body signing can only be disabled when using https. Defaults to `true`.
*
* @!attribute useAccelerateEndpoint
* @note This configuration option is only compatible with S3 while accessing
* dns-compatible buckets.
* @return [Boolean] Whether to use the Accelerate endpoint with the S3 service.
* Defaults to `false`.
*
* @!attribute retryDelayOptions
* @example Set the base retry delay for all services to 300 ms
* AWS.config.update({retryDelayOptions: {base: 300}});
* // Delays with maxRetries = 3: 300, 600, 1200
* @example Set a custom backoff function to provide delay values on retries
* AWS.config.update({retryDelayOptions: {customBackoff: function(retryCount) {
* // returns delay in ms
* }}});
* @note This works with all services except DynamoDB.
* @return [map] A set of options to configure the retry delay on retryable errors.
* Currently supported options are:
*
* * **base** [Integer] — The base number of milliseconds to use in the
* exponential backoff for operation retries. Defaults to 100 ms.
* * **customBackoff ** [function] — A custom function that accepts a retry count
* and returns the amount of time to delay in milliseconds. The `base` option will be
* ignored if this option is supplied.
*
* @!attribute httpOptions
* @return [map] A set of options to pass to the low-level HTTP request.
* Currently supported options are:
*
* * **proxy** [String] — the URL to proxy requests through
* * **agent** [http.Agent, https.Agent] — the Agent object to perform
* HTTP requests with. Used for connection pooling. Defaults to the global
* agent (`http.globalAgent`) for non-SSL connections. Note that for
* SSL connections, a special Agent object is used in order to enable
* peer certificate verification. This feature is only supported in the
* Node.js environment.
* * **timeout** [Integer] — The number of milliseconds to wait before
* giving up on a connection attempt. Defaults to two minutes (120000).
* * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous
* HTTP requests. Used in the browser environment only. Set to false to
* send requests synchronously. Defaults to true (async on).
* * **xhrWithCredentials** [Boolean] — Sets the "withCredentials"
* property of an XMLHttpRequest object. Used in the browser environment
* only. Defaults to false.
* @!attribute logger
* @return [#write,#log] an object that responds to .write() (like a stream)
* or .log() (like the console object) in order to log information about
* requests
*
* @!attribute systemClockOffset
* @return [Number] an offset value in milliseconds to apply to all signing
* times. Use this to compensate for clock skew when your system may be
* out of sync with the service time. Note that this configuration option
* can only be applied to the global `AWS.config` object and cannot be
* overridden in service-specific configuration. Defaults to 0 milliseconds.
*
* @!attribute signatureVersion
* @return [String] the signature version to sign requests with (overriding
* the API configuration). Possible values are: 'v2', 'v3', 'v4'.
*
* @!attribute signatureCache
* @return [Boolean] whether the signature to sign requests with (overriding
* the API configuration) is cached. Only applies to the signature version 'v4'.
* Defaults to `true`.
*/
AWS.Config = AWS.util.inherit({
/**
* @!endgroup
*/
/**
* Creates a new configuration object. This is the object that passes
* option data along to service requests, including credentials, security,
* region information, and some service specific settings.
*
* @example Creating a new configuration object with credentials and region
* var config = new AWS.Config({
* accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2'
* });
* @option options accessKeyId [String] your AWS access key ID.
* @option options secretAccessKey [String] your AWS secret access key.
* @option options sessionToken [AWS.Credentials] the optional AWS
* session token to sign requests with.
* @option options credentials [AWS.Credentials] the AWS credentials
* to sign requests with. You can either specify this object, or
* specify the accessKeyId and secretAccessKey options directly.
* @option options credentialProvider [AWS.CredentialProviderChain] the
* provider chain used to resolve credentials if no static `credentials`
* property is set.
* @option options region [String] the region to send service requests to.
* See {region} for more information.
* @option options maxRetries [Integer] the maximum amount of retries to
* attempt with a request. See {maxRetries} for more information.
* @option options maxRedirects [Integer] the maximum amount of redirects to
* follow with a request. See {maxRedirects} for more information.
* @option options sslEnabled [Boolean] whether to enable SSL for
* requests.
* @option options paramValidation [Boolean|map] whether input parameters
* should be validated against the operation description before sending
* the request. Defaults to true. Pass a map to enable any of the
* following specific validation features:
*
* * **min** [Boolean] — Validates that a value meets the min
* constraint. This is enabled by default when paramValidation is set
* to `true`.
* * **max** [Boolean] — Validates that a value meets the max
* constraint.
* * **pattern** [Boolean] — Validates that a string value matches a
* regular expression.
* * **enum** [Boolean] — Validates that a string value matches one
* of the allowable enum values.
* @option options computeChecksums [Boolean] whether to compute checksums
* for payload bodies when the service accepts it (currently supported
* in S3 only)
* @option options convertResponseTypes [Boolean] whether types are converted
* when parsing response data. Currently only supported for JSON based
* services. Turning this off may improve performance on large response
* payloads. Defaults to `true`.
* @option options correctClockSkew [Boolean] whether to apply a clock skew
* correction and retry requests that fail because of an skewed client
* clock. Defaults to `false`.
* @option options s3ForcePathStyle [Boolean] whether to force path
* style URLs for S3 objects.
* @option options s3BucketEndpoint [Boolean] whether the provided endpoint
* addresses an individual bucket (false if it addresses the root API
* endpoint). Note that setting this configuration option requires an
* `endpoint` to be provided explicitly to the service constructor.
* @option options s3DisableBodySigning [Boolean] whether S3 body signing
* should be disabled when using signature version `v4`. Body signing
* can only be disabled when using https. Defaults to `true`.
*
* @option options retryDelayOptions [map] A set of options to configure
* the retry delay on retryable errors. Currently supported options are:
*
* * **base** [Integer] — The base number of milliseconds to use in the
* exponential backoff for operation retries. Defaults to 100 ms.
* * **customBackoff ** [function] — A custom function that accepts a retry count
* and returns the amount of time to delay in milliseconds. The `base` option will be
* ignored if this option is supplied.
* @option options httpOptions [map] A set of options to pass to the low-level
* HTTP request. Currently supported options are:
*
* * **proxy** [String] — the URL to proxy requests through
* * **agent** [http.Agent, https.Agent] — the Agent object to perform
* HTTP requests with. Used for connection pooling. Defaults to the global
* agent (`http.globalAgent`) for non-SSL connections. Note that for
* SSL connections, a special Agent object is used in order to enable
* peer certificate verification. This feature is only available in the
* Node.js environment.
* * **timeout** [Integer] — Sets the socket to timeout after timeout
* milliseconds of inactivity on the socket. Defaults to two minutes
* (120000).
* * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous
* HTTP requests. Used in the browser environment only. Set to false to
* send requests synchronously. Defaults to true (async on).
* * **xhrWithCredentials** [Boolean] — Sets the "withCredentials"
* property of an XMLHttpRequest object. Used in the browser environment
* only. Defaults to false.
* @option options apiVersion [String, Date] a String in YYYY-MM-DD format
* (or a date) that represents the latest possible API version that can be
* used in all services (unless overridden by `apiVersions`). Specify
* 'latest' to use the latest possible version.
* @option options apiVersions [map<String, String|Date>] a map of service
* identifiers (the lowercase service class name) with the API version to
* use when instantiating a service. Specify 'latest' for each individual
* that can use the latest available version.
* @option options logger [#write,#log] an object that responds to .write()
* (like a stream) or .log() (like the console object) in order to log
* information about requests
* @option options systemClockOffset [Number] an offset value in milliseconds
* to apply to all signing times. Use this to compensate for clock skew
* when your system may be out of sync with the service time. Note that
* this configuration option can only be applied to the global `AWS.config`
* object and cannot be overridden in service-specific configuration.
* Defaults to 0 milliseconds.
* @option options signatureVersion [String] the signature version to sign
* requests with (overriding the API configuration). Possible values are:
* 'v2', 'v3', 'v4'.
* @option options signatureCache [Boolean] whether the signature to sign
* requests with (overriding the API configuration) is cached. Only applies
* to the signature version 'v4'. Defaults to `true`.
*/
constructor: function Config(options) {
Eif (options === undefined) options = {};
options = this.extractCredentials(options);
AWS.util.each.call(this, this.keys, function (key, value) {
this.set(key, options[key], value);
});
},
/**
* @!group Managing Credentials
*/
/**
* Loads credentials from the configuration object. This is used internally
* by the SDK to ensure that refreshable {Credentials} objects are properly
* refreshed and loaded when sending a request. If you want to ensure that
* your credentials are loaded prior to a request, you can use this method
* directly to provide accurate credential data stored in the object.
*
* @note If you configure the SDK with static or environment credentials,
* the credential data should already be present in {credentials} attribute.
* This method is primarily necessary to load credentials from asynchronous
* sources, or sources that can refresh credentials periodically.
* @example Getting your access key
* AWS.config.getCredentials(function(err) {
* if (err) console.log(err.stack); // credentials not loaded
* else console.log("Access Key:", AWS.config.credentials.accessKeyId);
* })
* @callback callback function(err)
* Called when the {credentials} have been properly set on the configuration
* object.
*
* @param err [Error] if this is set, credentials were not successfuly
* loaded and this error provides information why.
* @see credentials
* @see Credentials
*/
getCredentials: function getCredentials(callback) {
var self = this;
function finish(err) {
callback(err, err ? null : self.credentials);
}
function credError(msg, err) {
return new AWS.util.error(err || new Error(), {
code: 'CredentialsError', message: msg
});
}
function getAsyncCredentials() {
self.credentials.get(function(err) {
if (err) {
var msg = 'Could not load credentials from ' +
self.credentials.constructor.name;
err = credError(msg, err);
}
finish(err);
});
}
function getStaticCredentials() {
var err = null;
if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) {
err = credError('Missing credentials');
}
finish(err);
}
if (self.credentials) {
if (typeof self.credentials.get === 'function') {
getAsyncCredentials();
} else { // static credentials
getStaticCredentials();
}
} else if (self.credentialProvider) {
self.credentialProvider.resolve(function(err, creds) {
if (err) {
err = credError('Could not load credentials from any providers', err);
}
self.credentials = creds;
finish(err);
});
} else {
finish(credError('No credentials to load'));
}
},
/**
* @!group Loading and Setting Configuration Options
*/
/**
* @overload update(options, allowUnknownKeys = false)
* Updates the current configuration object with new options.
*
* @example Update maxRetries property of a configuration object
* config.update({maxRetries: 10});
* @param [Object] options a map of option keys and values.
* @param [Boolean] allowUnknownKeys whether unknown keys can be set on
* the configuration object. Defaults to `false`.
* @see constructor
*/
update: function update(options, allowUnknownKeys) {
allowUnknownKeys = allowUnknownKeys || false;
options = this.extractCredentials(options);
AWS.util.each.call(this, options, function (key, value) {
if (allowUnknownKeys || Object.prototype.hasOwnProperty.call(this.keys, key) ||
AWS.Service.hasService(key)) {
this.set(key, value);
}
});
},
/**
* Loads configuration data from a JSON file into this config object.
* @note Loading configuration will reset all existing configuration
* on the object.
* @!macro nobrowser
* @param path [String] the path relative to your process's current
* working directory to load configuration from.
* @return [AWS.Config] the same configuration object
*/
loadFromPath: function loadFromPath(path) {
this.clear();
var options = JSON.parse(AWS.util.readFileSync(path));
var fileSystemCreds = new AWS.FileSystemCredentials(path);
var chain = new AWS.CredentialProviderChain();
chain.providers.unshift(fileSystemCreds);
chain.resolve(function (err, creds) {
if (err) throw err;
else options.credentials = creds;
});
this.constructor(options);
return this;
},
/**
* Clears configuration data on this object
*
* @api private
*/
clear: function clear() {
/*jshint forin:false */
AWS.util.each.call(this, this.keys, function (key) {
delete this[key];
});
// reset credential provider
this.set('credentials', undefined);
this.set('credentialProvider', undefined);
},
/**
* Sets a property on the configuration object, allowing for a
* default value
* @api private
*/
set: function set(property, value, defaultValue) {
Eif (value === undefined) {
if (defaultValue === undefined) {
defaultValue = this.keys[property];
}
if (typeof defaultValue === 'function') {
this[property] = defaultValue.call(this);
} else {
this[property] = defaultValue;
}
} else if (property === 'httpOptions' && this[property]) {
// deep merge httpOptions
this[property] = AWS.util.merge(this[property], value);
} else {
this[property] = value;
}
},
/**
* All of the keys with their default values.
*
* @constant
* @api private
*/
keys: {
credentials: null,
credentialProvider: null,
region: null,
logger: null,
apiVersions: {},
apiVersion: null,
endpoint: undefined,
httpOptions: {
timeout: 120000
},
maxRetries: undefined,
maxRedirects: 10,
paramValidation: true,
sslEnabled: true,
s3ForcePathStyle: false,
s3BucketEndpoint: false,
s3DisableBodySigning: true,
computeChecksums: true,
convertResponseTypes: true,
correctClockSkew: false,
customUserAgent: null,
dynamoDbCrc32: true,
systemClockOffset: 0,
signatureVersion: null,
signatureCache: true,
retryDelayOptions: {
base: 100
},
useAccelerateEndpoint: false
},
/**
* Extracts accessKeyId, secretAccessKey and sessionToken
* from a configuration hash.
*
* @api private
*/
extractCredentials: function extractCredentials(options) {
Iif (options.accessKeyId && options.secretAccessKey) {
options = AWS.util.copy(options);
options.credentials = new AWS.Credentials(options);
}
return options;
},
/**
* Sets the promise dependency the SDK will use wherever Promises are returned.
* @param [Constructor] dep A reference to a Promise constructor
*/
setPromisesDependency: function setPromisesDependency(dep) {
AWS.util.addPromisesToRequests(AWS.Request, dep);
}
});
/**
* @return [AWS.Config] The global configuration object singleton instance
* @readonly
* @see AWS.Config
*/
AWS.config = new AWS.Config();
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | /**
* The main AWS namespace
*/
var AWS = { util: require('./util') };
/**
* @api private
* @!macro [new] nobrowser
* @note This feature is not supported in the browser environment of the SDK.
*/
var _hidden = {}; _hidden.toString(); // hack to parse macro
module.exports = AWS;
AWS.util.update(AWS, {
/**
* @constant
*/
VERSION: '2.5.2',
/**
* @api private
*/
Signers: {},
/**
* @api private
*/
Protocol: {
Json: require('./protocol/json'),
Query: require('./protocol/query'),
Rest: require('./protocol/rest'),
RestJson: require('./protocol/rest_json'),
RestXml: require('./protocol/rest_xml')
},
/**
* @api private
*/
XML: {
Builder: require('./xml/builder'),
Parser: null // conditionally set based on environment
},
/**
* @api private
*/
JSON: {
Builder: require('./json/builder'),
Parser: require('./json/parser')
},
/**
* @api private
*/
Model: {
Api: require('./model/api'),
Operation: require('./model/operation'),
Shape: require('./model/shape'),
Paginator: require('./model/paginator'),
ResourceWaiter: require('./model/resource_waiter')
},
util: require('./util'),
/**
* @api private
*/
apiLoader: function() { throw new Error('No API loader set'); }
});
require('./service');
require('./credentials');
require('./credentials/credential_provider_chain');
require('./credentials/temporary_credentials');
require('./credentials/web_identity_credentials');
require('./credentials/cognito_identity_credentials');
require('./credentials/saml_credentials');
require('./config');
require('./http');
require('./sequential_executor');
require('./event_listeners');
require('./request');
require('./response');
require('./resource_waiter');
require('./signers/request_signer');
require('./param_validator');
/**
* @readonly
* @return [AWS.SequentialExecutor] a collection of global event listeners that
* are attached to every sent request.
* @see AWS.Request AWS.Request for a list of events to listen for
* @example Logging the time taken to send a request
* AWS.events.on('send', function startSend(resp) {
* resp.startTime = new Date().getTime();
* }).on('complete', function calculateTime(resp) {
* var time = (new Date().getTime() - resp.startTime) / 1000;
* console.log('Request took ' + time + ' seconds');
* });
*
* new AWS.S3().listBuckets(); // prints 'Request took 0.285 seconds'
*/
AWS.events = new AWS.SequentialExecutor();
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | 1 1 3 3 3 3 3 3 3 6 6 6 6 6 6 6 6 6 | var AWS = require('./core');
/**
* Represents your AWS security credentials, specifically the
* {accessKeyId}, {secretAccessKey}, and optional {sessionToken}.
* Creating a `Credentials` object allows you to pass around your
* security information to configuration and service objects.
*
* Note that this class typically does not need to be constructed manually,
* as the {AWS.Config} and {AWS.Service} classes both accept simple
* options hashes with the three keys. These structures will be converted
* into Credentials objects automatically.
*
* ## Expiring and Refreshing Credentials
*
* Occasionally credentials can expire in the middle of a long-running
* application. In this case, the SDK will automatically attempt to
* refresh the credentials from the storage location if the Credentials
* class implements the {refresh} method.
*
* If you are implementing a credential storage location, you
* will want to create a subclass of the `Credentials` class and
* override the {refresh} method. This method allows credentials to be
* retrieved from the backing store, be it a file system, database, or
* some network storage. The method should reset the credential attributes
* on the object.
*
* @!attribute expired
* @return [Boolean] whether the credentials have been expired and
* require a refresh. Used in conjunction with {expireTime}.
* @!attribute expireTime
* @return [Date] a time when credentials should be considered expired. Used
* in conjunction with {expired}.
* @!attribute accessKeyId
* @return [String] the AWS access key ID
* @!attribute secretAccessKey
* @return [String] the AWS secret access key
* @!attribute sessionToken
* @return [String] an optional AWS session token
*/
AWS.Credentials = AWS.util.inherit({
/**
* A credentials object can be created using positional arguments or an options
* hash.
*
* @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null)
* Creates a Credentials object with a given set of credential information
* as positional arguments.
* @param accessKeyId [String] the AWS access key ID
* @param secretAccessKey [String] the AWS secret access key
* @param sessionToken [String] the optional AWS session token
* @example Create a credentials object with AWS credentials
* var creds = new AWS.Credentials('akid', 'secret', 'session');
* @overload AWS.Credentials(options)
* Creates a Credentials object with a given set of credential information
* as an options hash.
* @option options accessKeyId [String] the AWS access key ID
* @option options secretAccessKey [String] the AWS secret access key
* @option options sessionToken [String] the optional AWS session token
* @example Create a credentials object with AWS credentials
* var creds = new AWS.Credentials({
* accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session'
* });
*/
constructor: function Credentials() {
// hide secretAccessKey from being displayed with util.inspect
AWS.util.hideProperties(this, ['secretAccessKey']);
this.expired = false;
this.expireTime = null;
Iif (arguments.length === 1 && typeof arguments[0] === 'object') {
var creds = arguments[0].credentials || arguments[0];
this.accessKeyId = creds.accessKeyId;
this.secretAccessKey = creds.secretAccessKey;
this.sessionToken = creds.sessionToken;
} else {
this.accessKeyId = arguments[0];
this.secretAccessKey = arguments[1];
this.sessionToken = arguments[2];
}
},
/**
* @return [Integer] the window size in seconds to attempt refreshing of
* credentials before the expireTime occurs.
*/
expiryWindow: 15,
/**
* @return [Boolean] whether the credentials object should call {refresh}
* @note Subclasses should override this method to provide custom refresh
* logic.
*/
needsRefresh: function needsRefresh() {
var currentTime = AWS.util.date.getDate().getTime();
var adjustedTime = new Date(currentTime + this.expiryWindow * 1000);
Iif (this.expireTime && adjustedTime > this.expireTime) {
return true;
} else {
return this.expired || !this.accessKeyId || !this.secretAccessKey;
}
},
/**
* Gets the existing credentials, refreshing them if they are not yet loaded
* or have expired. Users should call this method before using {refresh},
* as this will not attempt to reload credentials when they are already
* loaded into the object.
*
* @callback callback function(err)
* Called when the instance metadata service responds (or fails). When
* this callback is called with no error, it means that the credentials
* information has been loaded into the object (as the `accessKeyId`,
* `secretAccessKey`, and `sessionToken` properties).
* @param err [Error] if an error occurred, this value will be filled
*/
get: function get(callback) {
var self = this;
Eif (this.needsRefresh()) {
this.refresh(function(err) {
Iif (!err) self.expired = false; // reset expired flag
Eif (callback) callback(err);
});
} else if (callback) {
callback();
}
},
/**
* Refreshes the credentials. Users should call {get} before attempting
* to forcibly refresh credentials.
*
* @callback callback function(err)
* Called when the instance metadata service responds (or fails). When
* this callback is called with no error, it means that the credentials
* information has been loaded into the object (as the `accessKeyId`,
* `secretAccessKey`, and `sessionToken` properties).
* @param err [Error] if an error occurred, this value will be filled
* @note Subclasses should override this class to reset the
* {accessKeyId}, {secretAccessKey} and optional {sessionToken}
* on the credentials object and then call the callback with
* any error information.
* @see get
*/
refresh: function refresh(callback) {
this.expired = false;
callback();
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | var AWS = require('./core');
var SequentialExecutor = require('./sequential_executor');
/**
* The namespace used to register global event listeners for request building
* and sending.
*/
AWS.EventListeners = {
/**
* @!attribute VALIDATE_CREDENTIALS
* A request listener that validates whether the request is being
* sent with credentials.
* Handles the {AWS.Request~validate 'validate' Request event}
* @example Sending a request without validating credentials
* var listener = AWS.EventListeners.Core.VALIDATE_CREDENTIALS;
* request.removeListener('validate', listener);
* @readonly
* @return [Function]
* @!attribute VALIDATE_REGION
* A request listener that validates whether the region is set
* for a request.
* Handles the {AWS.Request~validate 'validate' Request event}
* @example Sending a request without validating region configuration
* var listener = AWS.EventListeners.Core.VALIDATE_REGION;
* request.removeListener('validate', listener);
* @readonly
* @return [Function]
* @!attribute VALIDATE_PARAMETERS
* A request listener that validates input parameters in a request.
* Handles the {AWS.Request~validate 'validate' Request event}
* @example Sending a request without validating parameters
* var listener = AWS.EventListeners.Core.VALIDATE_PARAMETERS;
* request.removeListener('validate', listener);
* @example Disable parameter validation globally
* AWS.EventListeners.Core.removeListener('validate',
* AWS.EventListeners.Core.VALIDATE_REGION);
* @readonly
* @return [Function]
* @!attribute SEND
* A request listener that initiates the HTTP connection for a
* request being sent. Handles the {AWS.Request~send 'send' Request event}
* @example Replacing the HTTP handler
* var listener = AWS.EventListeners.Core.SEND;
* request.removeListener('send', listener);
* request.on('send', function(response) {
* customHandler.send(response);
* });
* @return [Function]
* @readonly
* @!attribute HTTP_DATA
* A request listener that reads data from the HTTP connection in order
* to build the response data.
* Handles the {AWS.Request~httpData 'httpData' Request event}.
* Remove this handler if you are overriding the 'httpData' event and
* do not want extra data processing and buffering overhead.
* @example Disabling default data processing
* var listener = AWS.EventListeners.Core.HTTP_DATA;
* request.removeListener('httpData', listener);
* @return [Function]
* @readonly
*/
Core: {} /* doc hack */
};
AWS.EventListeners = {
Core: new SequentialExecutor().addNamedListeners(function(add, addAsync) {
addAsync('VALIDATE_CREDENTIALS', 'validate',
function VALIDATE_CREDENTIALS(req, done) {
if (!req.service.api.signatureVersion) return done(); // none
req.service.config.getCredentials(function(err) {
if (err) {
req.response.error = AWS.util.error(err,
{code: 'CredentialsError', message: 'Missing credentials in config'});
}
done();
});
});
add('VALIDATE_REGION', 'validate', function VALIDATE_REGION(req) {
if (!req.service.config.region && !req.service.isGlobalEndpoint) {
req.response.error = AWS.util.error(new Error(),
{code: 'ConfigError', message: 'Missing region in config'});
}
});
add('VALIDATE_PARAMETERS', 'validate', function VALIDATE_PARAMETERS(req) {
var rules = req.service.api.operations[req.operation].input;
var validation = req.service.config.paramValidation;
new AWS.ParamValidator(validation).validate(rules, req.params);
});
addAsync('COMPUTE_SHA256', 'afterBuild', function COMPUTE_SHA256(req, done) {
req.haltHandlersOnError();
if (!req.service.api.signatureVersion) return done(); // none
if (req.service.getSignerClass(req) === AWS.Signers.V4) {
var body = req.httpRequest.body || '';
AWS.util.computeSha256(body, function(err, sha) {
if (err) {
done(err);
}
else {
req.httpRequest.headers['X-Amz-Content-Sha256'] = sha;
done();
}
});
} else {
done();
}
});
add('SET_CONTENT_LENGTH', 'afterBuild', function SET_CONTENT_LENGTH(req) {
if (req.httpRequest.headers['Content-Length'] === undefined) {
var length = AWS.util.string.byteLength(req.httpRequest.body);
req.httpRequest.headers['Content-Length'] = length;
}
});
add('SET_HTTP_HOST', 'afterBuild', function SET_HTTP_HOST(req) {
req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host;
});
add('RESTART', 'restart', function RESTART() {
var err = this.response.error;
if (!err || !err.retryable) return;
this.httpRequest = new AWS.HttpRequest(
this.service.endpoint,
this.service.region
);
if (this.response.retryCount < this.service.config.maxRetries) {
this.response.retryCount++;
} else {
this.response.error = null;
}
});
addAsync('SIGN', 'sign', function SIGN(req, done) {
var service = req.service;
if (!service.api.signatureVersion) return done(); // none
service.config.getCredentials(function (err, credentials) {
if (err) {
req.response.error = err;
return done();
}
try {
var date = AWS.util.date.getDate();
var SignerClass = service.getSignerClass(req);
var signer = new SignerClass(req.httpRequest,
service.api.signingName || service.api.endpointPrefix,
service.config.signatureCache);
signer.setServiceClientId(service._clientId);
// clear old authorization headers
delete req.httpRequest.headers['Authorization'];
delete req.httpRequest.headers['Date'];
delete req.httpRequest.headers['X-Amz-Date'];
// add new authorization
signer.addAuthorization(credentials, date);
req.signedAt = date;
} catch (e) {
req.response.error = e;
}
done();
});
});
add('VALIDATE_RESPONSE', 'validateResponse', function VALIDATE_RESPONSE(resp) {
if (this.service.successfulResponse(resp, this)) {
resp.data = {};
resp.error = null;
} else {
resp.data = null;
resp.error = AWS.util.error(new Error(),
{code: 'UnknownError', message: 'An unknown error occurred.'});
}
});
addAsync('SEND', 'send', function SEND(resp, done) {
resp.httpResponse._abortCallback = done;
resp.error = null;
resp.data = null;
function callback(httpResp) {
resp.httpResponse.stream = httpResp;
httpResp.on('headers', function onHeaders(statusCode, headers) {
resp.request.emit('httpHeaders', [statusCode, headers, resp]);
if (!resp.httpResponse.streaming) {
if (AWS.HttpClient.streamsApiVersion === 2) { // streams2 API check
httpResp.on('readable', function onReadable() {
var data = httpResp.read();
if (data !== null) {
resp.request.emit('httpData', [data, resp]);
}
});
} else { // legacy streams API
httpResp.on('data', function onData(data) {
resp.request.emit('httpData', [data, resp]);
});
}
}
});
httpResp.on('end', function onEnd() {
resp.request.emit('httpDone');
done();
});
}
function progress(httpResp) {
httpResp.on('sendProgress', function onSendProgress(value) {
resp.request.emit('httpUploadProgress', [value, resp]);
});
httpResp.on('receiveProgress', function onReceiveProgress(value) {
resp.request.emit('httpDownloadProgress', [value, resp]);
});
}
function error(err) {
resp.error = AWS.util.error(err, {
code: 'NetworkingError',
region: resp.request.httpRequest.region,
hostname: resp.request.httpRequest.endpoint.hostname,
retryable: true
});
resp.request.emit('httpError', [resp.error, resp], function() {
done();
});
}
function executeSend() {
var http = AWS.HttpClient.getInstance();
var httpOptions = resp.request.service.config.httpOptions || {};
try {
var stream = http.handleRequest(resp.request.httpRequest, httpOptions,
callback, error);
progress(stream);
} catch (err) {
error(err);
}
}
var timeDiff = (AWS.util.date.getDate() - this.signedAt) / 1000;
if (timeDiff >= 60 * 10) { // if we signed 10min ago, re-sign
this.emit('sign', [this], function(err) {
if (err) done(err);
else executeSend();
});
} else {
executeSend();
}
});
add('HTTP_HEADERS', 'httpHeaders',
function HTTP_HEADERS(statusCode, headers, resp) {
resp.httpResponse.statusCode = statusCode;
resp.httpResponse.headers = headers;
resp.httpResponse.body = new AWS.util.Buffer('');
resp.httpResponse.buffers = [];
resp.httpResponse.numBytes = 0;
var dateHeader = headers.date || headers.Date;
if (dateHeader) {
var serverTime = Date.parse(dateHeader);
if (resp.request.service.config.correctClockSkew
&& AWS.util.isClockSkewed(serverTime)) {
AWS.util.applyClockOffset(serverTime);
}
}
});
add('HTTP_DATA', 'httpData', function HTTP_DATA(chunk, resp) {
if (chunk) {
if (AWS.util.isNode()) {
resp.httpResponse.numBytes += chunk.length;
var total = resp.httpResponse.headers['content-length'];
var progress = { loaded: resp.httpResponse.numBytes, total: total };
resp.request.emit('httpDownloadProgress', [progress, resp]);
}
resp.httpResponse.buffers.push(new AWS.util.Buffer(chunk));
}
});
add('HTTP_DONE', 'httpDone', function HTTP_DONE(resp) {
// convert buffers array into single buffer
if (resp.httpResponse.buffers && resp.httpResponse.buffers.length > 0) {
var body = AWS.util.buffer.concat(resp.httpResponse.buffers);
resp.httpResponse.body = body;
}
delete resp.httpResponse.numBytes;
delete resp.httpResponse.buffers;
});
add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(resp) {
if (resp.httpResponse.statusCode) {
resp.error.statusCode = resp.httpResponse.statusCode;
if (resp.error.retryable === undefined) {
resp.error.retryable = this.service.retryableError(resp.error, this);
}
}
});
add('INVALIDATE_CREDENTIALS', 'retry', function INVALIDATE_CREDENTIALS(resp) {
if (!resp.error) return;
switch (resp.error.code) {
case 'RequestExpired': // EC2 only
case 'ExpiredTokenException':
case 'ExpiredToken':
resp.error.retryable = true;
resp.request.service.config.credentials.expired = true;
}
});
add('EXPIRED_SIGNATURE', 'retry', function EXPIRED_SIGNATURE(resp) {
var err = resp.error;
if (!err) return;
if (typeof err.code === 'string' && typeof err.message === 'string') {
if (err.code.match(/Signature/) && err.message.match(/expired/)) {
resp.error.retryable = true;
}
}
});
add('CLOCK_SKEWED', 'retry', function CLOCK_SKEWED(resp) {
if (!resp.error) return;
if (this.service.clockSkewError(resp.error)
&& this.service.config.correctClockSkew
&& AWS.config.isClockSkewed) {
resp.error.retryable = true;
}
});
add('REDIRECT', 'retry', function REDIRECT(resp) {
if (resp.error && resp.error.statusCode >= 300 &&
resp.error.statusCode < 400 && resp.httpResponse.headers['location']) {
this.httpRequest.endpoint =
new AWS.Endpoint(resp.httpResponse.headers['location']);
this.httpRequest.headers['Host'] = this.httpRequest.endpoint.host;
resp.error.redirect = true;
resp.error.retryable = true;
}
});
add('RETRY_CHECK', 'retry', function RETRY_CHECK(resp) {
if (resp.error) {
if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
resp.error.retryDelay = 0;
} else if (resp.retryCount < resp.maxRetries) {
resp.error.retryDelay = this.service.retryDelays(resp.retryCount) || 0;
}
}
});
addAsync('RESET_RETRY_STATE', 'afterRetry', function RESET_RETRY_STATE(resp, done) {
var delay, willRetry = false;
if (resp.error) {
delay = resp.error.retryDelay || 0;
if (resp.error.retryable && resp.retryCount < resp.maxRetries) {
resp.retryCount++;
willRetry = true;
} else if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
resp.redirectCount++;
willRetry = true;
}
}
if (willRetry) {
resp.error = null;
setTimeout(done, delay);
} else {
done();
}
});
}),
CorePost: new SequentialExecutor().addNamedListeners(function(add) {
add('EXTRACT_REQUEST_ID', 'extractData', AWS.util.extractRequestId);
add('EXTRACT_REQUEST_ID', 'extractError', AWS.util.extractRequestId);
add('ENOTFOUND_ERROR', 'httpError', function ENOTFOUND_ERROR(err) {
if (err.code === 'NetworkingError' && err.errno === 'ENOTFOUND') {
var message = 'Inaccessible host: `' + err.hostname +
'\'. This service may not be available in the `' + err.region +
'\' region.';
this.response.error = AWS.util.error(new Error(message), {
code: 'UnknownEndpoint',
region: err.region,
hostname: err.hostname,
retryable: true,
originalError: err
});
}
});
}),
Logger: new SequentialExecutor().addNamedListeners(function(add) {
add('LOG_REQUEST', 'complete', function LOG_REQUEST(resp) {
var req = resp.request;
var logger = req.service.config.logger;
if (!logger) return;
function buildMessage() {
var time = AWS.util.date.getDate().getTime();
var delta = (time - req.startTime.getTime()) / 1000;
var ansi = logger.isTTY ? true : false;
var status = resp.httpResponse.statusCode;
var params = require('util').inspect(req.params, true, null);
var message = '';
if (ansi) message += '\x1B[33m';
message += '[AWS ' + req.service.serviceIdentifier + ' ' + status;
message += ' ' + delta.toString() + 's ' + resp.retryCount + ' retries]';
if (ansi) message += '\x1B[0;1m';
message += ' ' + AWS.util.string.lowerFirst(req.operation);
message += '(' + params + ')';
if (ansi) message += '\x1B[0m';
return message;
}
var line = buildMessage();
if (typeof logger.log === 'function') {
logger.log(line);
} else if (typeof logger.write === 'function') {
logger.write(line + '\n');
}
});
}),
Json: new SequentialExecutor().addNamedListeners(function(add) {
var svc = require('./protocol/json');
add('BUILD', 'build', svc.buildRequest);
add('EXTRACT_DATA', 'extractData', svc.extractData);
add('EXTRACT_ERROR', 'extractError', svc.extractError);
}),
Rest: new SequentialExecutor().addNamedListeners(function(add) {
var svc = require('./protocol/rest');
add('BUILD', 'build', svc.buildRequest);
add('EXTRACT_DATA', 'extractData', svc.extractData);
add('EXTRACT_ERROR', 'extractError', svc.extractError);
}),
RestJson: new SequentialExecutor().addNamedListeners(function(add) {
var svc = require('./protocol/rest_json');
add('BUILD', 'build', svc.buildRequest);
add('EXTRACT_DATA', 'extractData', svc.extractData);
add('EXTRACT_ERROR', 'extractError', svc.extractError);
}),
RestXml: new SequentialExecutor().addNamedListeners(function(add) {
var svc = require('./protocol/rest_xml');
add('BUILD', 'build', svc.buildRequest);
add('EXTRACT_DATA', 'extractData', svc.extractData);
add('EXTRACT_ERROR', 'extractError', svc.extractError);
}),
Query: new SequentialExecutor().addNamedListeners(function(add) {
var svc = require('./protocol/query');
add('BUILD', 'build', svc.buildRequest);
add('EXTRACT_DATA', 'extractData', svc.extractData);
add('EXTRACT_ERROR', 'extractError', svc.extractError);
})
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | 1 1 1 1 1 1 1 | var AWS = require('./core');
var inherit = AWS.util.inherit;
/**
* The endpoint that a service will talk to, for example,
* `'https://ec2.ap-southeast-1.amazonaws.com'`. If
* you need to override an endpoint for a service, you can
* set the endpoint on a service by passing the endpoint
* object with the `endpoint` option key:
*
* ```javascript
* var ep = new AWS.Endpoint('awsproxy.example.com');
* var s3 = new AWS.S3({endpoint: ep});
* s3.service.endpoint.hostname == 'awsproxy.example.com'
* ```
*
* Note that if you do not specify a protocol, the protocol will
* be selected based on your current {AWS.config} configuration.
*
* @!attribute protocol
* @return [String] the protocol (http or https) of the endpoint
* URL
* @!attribute hostname
* @return [String] the host portion of the endpoint, e.g.,
* example.com
* @!attribute host
* @return [String] the host portion of the endpoint including
* the port, e.g., example.com:80
* @!attribute port
* @return [Integer] the port of the endpoint
* @!attribute href
* @return [String] the full URL of the endpoint
*/
AWS.Endpoint = inherit({
/**
* @overload Endpoint(endpoint)
* Constructs a new endpoint given an endpoint URL. If the
* URL omits a protocol (http or https), the default protocol
* set in the global {AWS.config} will be used.
* @param endpoint [String] the URL to construct an endpoint from
*/
constructor: function Endpoint(endpoint, config) {
AWS.util.hideProperties(this, ['slashes', 'auth', 'hash', 'search', 'query']);
if (typeof endpoint === 'undefined' || endpoint === null) {
throw new Error('Invalid endpoint: ' + endpoint);
} else if (typeof endpoint !== 'string') {
return AWS.util.copy(endpoint);
}
if (!endpoint.match(/^http/)) {
var useSSL = config && config.sslEnabled !== undefined ?
config.sslEnabled : AWS.config.sslEnabled;
endpoint = (useSSL ? 'https' : 'http') + '://' + endpoint;
}
AWS.util.update(this, AWS.util.urlParse(endpoint));
// Ensure the port property is set as an integer
if (this.port) {
this.port = parseInt(this.port, 10);
} else {
this.port = this.protocol === 'https:' ? 443 : 80;
}
}
});
/**
* The low level HTTP request object, encapsulating all HTTP header
* and body data sent by a service request.
*
* @!attribute method
* @return [String] the HTTP method of the request
* @!attribute path
* @return [String] the path portion of the URI, e.g.,
* "/list/?start=5&num=10"
* @!attribute headers
* @return [map<String,String>]
* a map of header keys and their respective values
* @!attribute body
* @return [String] the request body payload
* @!attribute endpoint
* @return [AWS.Endpoint] the endpoint for the request
* @!attribute region
* @api private
* @return [String] the region, for signing purposes only.
*/
AWS.HttpRequest = inherit({
/**
* @api private
*/
constructor: function HttpRequest(endpoint, region, customUserAgent) {
endpoint = new AWS.Endpoint(endpoint);
this.method = 'POST';
this.path = endpoint.path || '/';
this.headers = {};
this.body = '';
this.endpoint = endpoint;
this.region = region;
this.setUserAgent(customUserAgent);
},
/**
* @api private
*/
setUserAgent: function setUserAgent(customUserAgent) {
var prefix = AWS.util.isBrowser() ? 'X-Amz-' : '';
var customSuffix = '';
if (typeof customUserAgent === 'string' && customUserAgent) {
customSuffix += ' ' + customUserAgent;
}
this.headers[prefix + 'User-Agent'] = AWS.util.userAgent() + customSuffix;
},
/**
* @return [String] the part of the {path} excluding the
* query string
*/
pathname: function pathname() {
return this.path.split('?', 1)[0];
},
/**
* @return [String] the query string portion of the {path}
*/
search: function search() {
var query = this.path.split('?', 2)[1];
if (query) {
query = AWS.util.queryStringParse(query);
return AWS.util.queryParamsToString(query);
}
return '';
}
});
/**
* The low level HTTP response object, encapsulating all HTTP header
* and body data returned from the request.
*
* @!attribute statusCode
* @return [Integer] the HTTP status code of the response (e.g., 200, 404)
* @!attribute headers
* @return [map<String,String>]
* a map of response header keys and their respective values
* @!attribute body
* @return [String] the response body payload
* @!attribute [r] streaming
* @return [Boolean] whether this response is being streamed at a low-level.
* Defaults to `false` (buffered reads). Do not modify this manually, use
* {createUnbufferedStream} to convert the stream to unbuffered mode
* instead.
*/
AWS.HttpResponse = inherit({
/**
* @api private
*/
constructor: function HttpResponse() {
this.statusCode = undefined;
this.headers = {};
this.body = undefined;
this.streaming = false;
this.stream = null;
},
/**
* Disables buffering on the HTTP response and returns the stream for reading.
* @return [Stream, XMLHttpRequest, null] the underlying stream object.
* Use this object to directly read data off of the stream.
* @note This object is only available after the {AWS.Request~httpHeaders}
* event has fired. This method must be called prior to
* {AWS.Request~httpData}.
* @example Taking control of a stream
* request.on('httpHeaders', function(statusCode, headers) {
* if (statusCode < 300) {
* if (headers.etag === 'xyz') {
* // pipe the stream, disabling buffering
* var stream = this.response.httpResponse.createUnbufferedStream();
* stream.pipe(process.stdout);
* } else { // abort this request and set a better error message
* this.abort();
* this.response.error = new Error('Invalid ETag');
* }
* }
* }).send(console.log);
*/
createUnbufferedStream: function createUnbufferedStream() {
this.streaming = true;
return this.stream;
}
});
AWS.HttpClient = inherit({});
/**
* @api private
*/
AWS.HttpClient.getInstance = function getInstance() {
if (this.singleton === undefined) {
this.singleton = new this();
}
return this.singleton;
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | 1 1 1 1 1 1 | var AWS = require('./core');
require('./http');
var inherit = AWS.util.inherit;
/**
* Represents a metadata service available on EC2 instances. Using the
* {request} method, you can receieve metadata about any available resource
* on the metadata service.
*
* @!attribute [r] httpOptions
* @return [map] a map of options to pass to the underlying HTTP request:
*
* * **timeout** (Number) — a timeout value in milliseconds to wait
* before aborting the connection. Set to 0 for no timeout.
*
* @!macro nobrowser
*/
AWS.MetadataService = inherit({
/**
* @return [String] the hostname of the instance metadata service
*/
host: '169.254.169.254',
/**
* @!ignore
*/
/**
* Default HTTP options. By default, the metadata service is set to not
* timeout on long requests. This means that on non-EC2 machines, this
* request will never return. If you are calling this operation from an
* environment that may not always run on EC2, set a `timeout` value so
* the SDK will abort the request after a given number of milliseconds.
*/
httpOptions: { timeout: 0 },
/**
* Creates a new MetadataService object with a given set of options.
*
* @option options host [String] the hostname of the instance metadata
* service
* @option options httpOptions [map] a map of options to pass to the
* underlying HTTP request:
*
* * **timeout** (Number) — a timeout value in milliseconds to wait
* before aborting the connection. Set to 0 for no timeout.
*/
constructor: function MetadataService(options) {
AWS.util.update(this, options);
},
/**
* Sends a request to the instance metadata service for a given resource.
*
* @param path [String] the path of the resource to get
* @callback callback function(err, data)
* Called when a response is available from the service.
* @param err [Error, null] if an error occurred, this value will be set
* @param data [String, null] if the request was successful, the body of
* the response
*/
request: function request(path, callback) {
path = path || '/';
var data = '';
var http = AWS.HttpClient.getInstance();
var httpRequest = new AWS.HttpRequest('http://' + this.host + path);
httpRequest.method = 'GET';
var httpOptions = this.httpOptions;
process.nextTick(function() {
http.handleRequest(httpRequest, httpOptions, function(httpResponse) {
httpResponse.on('data', function(chunk) { data += chunk.toString(); });
httpResponse.on('end', function() { callback(null, data); });
}, callback);
});
},
/**
* @api private
*/
loadCredentialsCallbacks: [],
/**
* Loads a set of credentials stored in the instance metadata service
*
* @api private
* @callback callback function(err, credentials)
* Called when credentials are loaded from the resource
* @param err [Error] if an error occurred, this value will be set
* @param credentials [Object] the raw JSON object containing all
* metadata from the credentials resource
*/
loadCredentials: function loadCredentials(callback) {
var self = this;
var basePath = '/latest/meta-data/iam/security-credentials/';
self.loadCredentialsCallbacks.push(callback);
if (self.loadCredentialsCallbacks.length > 1) { return; }
function callbacks(err, creds) {
var cb;
while ((cb = self.loadCredentialsCallbacks.shift()) !== undefined) {
cb(err, creds);
}
}
self.request(basePath, function (err, roleName) {
if (err) callbacks(err);
else {
roleName = roleName.split('\n')[0]; // grab first (and only) role
self.request(basePath + roleName, function (credErr, credData) {
if (credErr) callbacks(credErr);
else {
try {
var credentials = JSON.parse(credData);
callbacks(null, credentials);
} catch (parseError) {
callbacks(parseError);
}
}
});
}
});
}
});
module.exports = AWS.MetadataService;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 | 1 1 | var AWS = require('./core');
/**
* @api private
*/
AWS.ParamValidator = AWS.util.inherit({
/**
* Create a new validator object.
*
* @param validation [Boolean|map] whether input parameters should be
* validated against the operation description before sending the
* request. Pass a map to enable any of the following specific
* validation features:
*
* * **min** [Boolean] — Validates that a value meets the min
* constraint. This is enabled by default when paramValidation is set
* to `true`.
* * **max** [Boolean] — Validates that a value meets the max
* constraint.
* * **pattern** [Boolean] — Validates that a string value matches a
* regular expression.
* * **enum** [Boolean] — Validates that a string value matches one
* of the allowable enum values.
*/
constructor: function ParamValidator(validation) {
if (validation === true || validation === undefined) {
validation = {'min': true};
}
this.validation = validation;
},
validate: function validate(shape, params, context) {
this.errors = [];
this.validateMember(shape, params || {}, context || 'params');
if (this.errors.length > 1) {
var msg = this.errors.join('\n* ');
msg = 'There were ' + this.errors.length +
' validation errors:\n* ' + msg;
throw AWS.util.error(new Error(msg),
{code: 'MultipleValidationErrors', errors: this.errors});
} else if (this.errors.length === 1) {
throw this.errors[0];
} else {
return true;
}
},
fail: function fail(code, message) {
this.errors.push(AWS.util.error(new Error(message), {code: code}));
},
validateStructure: function validateStructure(shape, params, context) {
this.validateType(params, context, ['object'], 'structure');
var paramName;
for (var i = 0; shape.required && i < shape.required.length; i++) {
paramName = shape.required[i];
var value = params[paramName];
if (value === undefined || value === null) {
this.fail('MissingRequiredParameter',
'Missing required key \'' + paramName + '\' in ' + context);
}
}
// validate hash members
for (paramName in params) {
if (!Object.prototype.hasOwnProperty.call(params, paramName)) continue;
var paramValue = params[paramName],
memberShape = shape.members[paramName];
if (memberShape !== undefined) {
var memberContext = [context, paramName].join('.');
this.validateMember(memberShape, paramValue, memberContext);
} else {
this.fail('UnexpectedParameter',
'Unexpected key \'' + paramName + '\' found in ' + context);
}
}
return true;
},
validateMember: function validateMember(shape, param, context) {
switch (shape.type) {
case 'structure':
return this.validateStructure(shape, param, context);
case 'list':
return this.validateList(shape, param, context);
case 'map':
return this.validateMap(shape, param, context);
default:
return this.validateScalar(shape, param, context);
}
},
validateList: function validateList(shape, params, context) {
if (this.validateType(params, context, [Array])) {
this.validateRange(shape, params.length, context, 'list member count');
// validate array members
for (var i = 0; i < params.length; i++) {
this.validateMember(shape.member, params[i], context + '[' + i + ']');
}
}
},
validateMap: function validateMap(shape, params, context) {
if (this.validateType(params, context, ['object'], 'map')) {
// Build up a count of map members to validate range traits.
var mapCount = 0;
for (var param in params) {
if (!Object.prototype.hasOwnProperty.call(params, param)) continue;
// Validate any map key trait constraints
this.validateMember(shape.key, param,
context + '[key=\'' + param + '\']')
this.validateMember(shape.value, params[param],
context + '[\'' + param + '\']');
mapCount++;
}
this.validateRange(shape, mapCount, context, 'map member count');
}
},
validateScalar: function validateScalar(shape, value, context) {
switch (shape.type) {
case null:
case undefined:
case 'string':
return this.validateString(shape, value, context);
case 'base64':
case 'binary':
return this.validatePayload(value, context);
case 'integer':
case 'float':
return this.validateNumber(shape, value, context);
case 'boolean':
return this.validateType(value, context, ['boolean']);
case 'timestamp':
return this.validateType(value, context, [Date,
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/, 'number'],
'Date object, ISO-8601 string, or a UNIX timestamp');
default:
return this.fail('UnkownType', 'Unhandled type ' +
shape.type + ' for ' + context);
}
},
validateString: function validateString(shape, value, context) {
if (this.validateType(value, context, ['string'])) {
this.validateEnum(shape, value, context);
this.validateRange(shape, value.length, context, 'string length');
this.validatePattern(shape, value, context);
}
},
validatePattern: function validatePattern(shape, value, context) {
if (this.validation['pattern'] && shape['pattern'] !== undefined) {
if (!(new RegExp(shape['pattern'])).test(value)) {
this.fail('PatternMatchError', 'Provided value "' + value + '" '
+ 'does not match regex pattern /' + shape['pattern'] + '/ for '
+ context);
}
}
},
validateRange: function validateRange(shape, value, context, descriptor) {
if (this.validation['min']) {
if (shape['min'] !== undefined && value < shape['min']) {
this.fail('MinRangeError', 'Expected ' + descriptor + ' >= '
+ shape['min'] + ', but found ' + value + ' for ' + context);
}
}
if (this.validation['max']) {
if (shape['max'] !== undefined && value > shape['max']) {
this.fail('MaxRangeError', 'Expected ' + descriptor + ' <= '
+ shape['max'] + ', but found ' + value + ' for ' + context);
}
}
},
validateEnum: function validateRange(shape, value, context) {
if (this.validation['enum'] && shape['enum'] !== undefined) {
// Fail if the string value is not present in the enum list
if (shape['enum'].indexOf(value) === -1) {
this.fail('EnumError', 'Found string value of ' + value + ', but '
+ 'expected ' + shape['enum'].join('|') + ' for ' + context);
}
}
},
validateType: function validateType(value, context, acceptedTypes, type) {
// We will not log an error for null or undefined, but we will return
// false so that callers know that the expected type was not strictly met.
if (value === null || value === undefined) return false;
var foundInvalidType = false;
for (var i = 0; i < acceptedTypes.length; i++) {
if (typeof acceptedTypes[i] === 'string') {
if (typeof value === acceptedTypes[i]) return true;
} else if (acceptedTypes[i] instanceof RegExp) {
if ((value || '').toString().match(acceptedTypes[i])) return true;
} else {
if (value instanceof acceptedTypes[i]) return true;
if (AWS.util.isType(value, acceptedTypes[i])) return true;
if (!type && !foundInvalidType) acceptedTypes = acceptedTypes.slice();
acceptedTypes[i] = AWS.util.typeName(acceptedTypes[i]);
}
foundInvalidType = true;
}
var acceptedType = type;
if (!acceptedType) {
acceptedType = acceptedTypes.join(', ').replace(/,([^,]+)$/, ', or$1');
}
var vowel = acceptedType.match(/^[aeiou]/i) ? 'n' : '';
this.fail('InvalidParameterType', 'Expected ' + context + ' to be a' +
vowel + ' ' + acceptedType);
return false;
},
validateNumber: function validateNumber(shape, value, context) {
if (value === null || value === undefined) return;
if (typeof value === 'string') {
var castedValue = parseFloat(value);
if (castedValue.toString() === value) value = castedValue;
}
if (this.validateType(value, context, ['number'])) {
this.validateRange(shape, value, context, 'numeric value');
}
},
validatePayload: function validatePayload(value, context) {
if (value === null || value === undefined) return;
if (typeof value === 'string') return;
if (value && typeof value.byteLength === 'number') return; // typed arrays
if (AWS.util.isNode()) { // special check for buffer/stream in Node.js
var Stream = AWS.util.nodeRequire('stream').Stream;
if (AWS.util.Buffer.isBuffer(value) || value instanceof Stream) return;
}
var types = ['Buffer', 'Stream', 'File', 'Blob', 'ArrayBuffer', 'DataView'];
if (value) {
for (var i = 0; i < types.length; i++) {
if (AWS.util.isType(value, types[i])) return;
if (AWS.util.typeName(value.constructor) === types[i]) return;
}
}
this.fail('InvalidParameterType', 'Expected ' + context + ' to be a ' +
'string, Buffer, Stream, Blob, or typed array object');
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 1 1 1 1 1 1 1 | var util = require('./util');
var regionConfig = require('./region_config.json');
function generateRegionPrefix(region) {
if (!region) return null;
var parts = region.split('-');
if (parts.length < 3) return null;
return parts.slice(0, parts.length - 2).join('-') + '-*';
}
function derivedKeys(service) {
var region = service.config.region;
var regionPrefix = generateRegionPrefix(region);
var endpointPrefix = service.api.endpointPrefix;
return [
[region, endpointPrefix],
[regionPrefix, endpointPrefix],
[region, '*'],
[regionPrefix, '*'],
['*', endpointPrefix],
['*', '*']
].map(function(item) {
return item[0] && item[1] ? item.join('/') : null;
});
}
function applyConfig(service, config) {
util.each(config, function(key, value) {
if (key === 'globalEndpoint') return;
if (service.config[key] === undefined || service.config[key] === null) {
service.config[key] = value;
}
});
}
function configureEndpoint(service) {
var keys = derivedKeys(service);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!key) continue;
if (Object.prototype.hasOwnProperty.call(regionConfig.rules, key)) {
var config = regionConfig.rules[key];
if (typeof config === 'string') {
config = regionConfig.patterns[config];
}
// set dualstack endpoint
if (service.config.useDualstack && util.isDualstackAvailable(service)) {
config = util.copy(config);
config.endpoint = '{service}.dualstack.{region}.amazonaws.com';
}
// set global endpoint
service.isGlobalEndpoint = !!config.globalEndpoint;
// signature version
if (!config.signatureVersion) config.signatureVersion = 'v4';
// merge config
applyConfig(service, config);
return;
}
}
}
module.exports = configureEndpoint;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | var AWS = require('./core');
var AcceptorStateMachine = require('./state_machine');
var inherit = AWS.util.inherit;
var domain = AWS.util.nodeRequire('domain');
var jmespath = require('jmespath');
/**
* @api private
*/
var hardErrorStates = {success: 1, error: 1, complete: 1};
function isTerminalState(machine) {
return Object.prototype.hasOwnProperty.call(hardErrorStates, machine._asm.currentState);
}
var fsm = new AcceptorStateMachine();
fsm.setupStates = function() {
var transition = function(_, done) {
var self = this;
self._haltHandlersOnError = false;
self.emit(self._asm.currentState, function(err) {
if (err) {
if (isTerminalState(self)) {
if (domain && self.domain instanceof domain.Domain) {
err.domainEmitter = self;
err.domain = self.domain;
err.domainThrown = false;
self.domain.emit('error', err);
} else {
throw err;
}
} else {
self.response.error = err;
done(err);
}
} else {
done(self.response.error);
}
});
};
this.addState('validate', 'build', 'error', transition);
this.addState('build', 'afterBuild', 'restart', transition);
this.addState('afterBuild', 'sign', 'restart', transition);
this.addState('sign', 'send', 'retry', transition);
this.addState('retry', 'afterRetry', 'afterRetry', transition);
this.addState('afterRetry', 'sign', 'error', transition);
this.addState('send', 'validateResponse', 'retry', transition);
this.addState('validateResponse', 'extractData', 'extractError', transition);
this.addState('extractError', 'extractData', 'retry', transition);
this.addState('extractData', 'success', 'retry', transition);
this.addState('restart', 'build', 'error', transition);
this.addState('success', 'complete', 'complete', transition);
this.addState('error', 'complete', 'complete', transition);
this.addState('complete', null, null, transition);
};
fsm.setupStates();
/**
* ## Asynchronous Requests
*
* All requests made through the SDK are asynchronous and use a
* callback interface. Each service method that kicks off a request
* returns an `AWS.Request` object that you can use to register
* callbacks.
*
* For example, the following service method returns the request
* object as "request", which can be used to register callbacks:
*
* ```javascript
* // request is an AWS.Request object
* var request = ec2.describeInstances();
*
* // register callbacks on request to retrieve response data
* request.on('success', function(response) {
* console.log(response.data);
* });
* ```
*
* When a request is ready to be sent, the {send} method should
* be called:
*
* ```javascript
* request.send();
* ```
*
* ## Removing Default Listeners for Events
*
* Request objects are built with default listeners for the various events,
* depending on the service type. In some cases, you may want to remove
* some built-in listeners to customize behaviour. Doing this requires
* access to the built-in listener functions, which are exposed through
* the {AWS.EventListeners.Core} namespace. For instance, you may
* want to customize the HTTP handler used when sending a request. In this
* case, you can remove the built-in listener associated with the 'send'
* event, the {AWS.EventListeners.Core.SEND} listener and add your own.
*
* ## Multiple Callbacks and Chaining
*
* You can register multiple callbacks on any request object. The
* callbacks can be registered for different events, or all for the
* same event. In addition, you can chain callback registration, for
* example:
*
* ```javascript
* request.
* on('success', function(response) {
* console.log("Success!");
* }).
* on('error', function(response) {
* console.log("Error!");
* }).
* on('complete', function(response) {
* console.log("Always!");
* }).
* send();
* ```
*
* The above example will print either "Success! Always!", or "Error! Always!",
* depending on whether the request succeeded or not.
*
* @!attribute httpRequest
* @readonly
* @!group HTTP Properties
* @return [AWS.HttpRequest] the raw HTTP request object
* containing request headers and body information
* sent by the service.
*
* @!attribute startTime
* @readonly
* @!group Operation Properties
* @return [Date] the time that the request started
*
* @!group Request Building Events
*
* @!event validate(request)
* Triggered when a request is being validated. Listeners
* should throw an error if the request should not be sent.
* @param request [Request] the request object being sent
* @see AWS.EventListeners.Core.VALIDATE_CREDENTIALS
* @see AWS.EventListeners.Core.VALIDATE_REGION
* @example Ensuring that a certain parameter is set before sending a request
* var req = s3.putObject(params);
* req.on('validate', function() {
* if (!req.params.Body.match(/^Hello\s/)) {
* throw new Error('Body must start with "Hello "');
* }
* });
* req.send(function(err, data) { ... });
*
* @!event build(request)
* Triggered when the request payload is being built. Listeners
* should fill the necessary information to send the request
* over HTTP.
* @param (see AWS.Request~validate)
* @example Add a custom HTTP header to a request
* var req = s3.putObject(params);
* req.on('build', function() {
* req.httpRequest.headers['Custom-Header'] = 'value';
* });
* req.send(function(err, data) { ... });
*
* @!event sign(request)
* Triggered when the request is being signed. Listeners should
* add the correct authentication headers and/or adjust the body,
* depending on the authentication mechanism being used.
* @param (see AWS.Request~validate)
*
* @!group Request Sending Events
*
* @!event send(response)
* Triggered when the request is ready to be sent. Listeners
* should call the underlying transport layer to initiate
* the sending of the request.
* @param response [Response] the response object
* @context [Request] the request object that was sent
* @see AWS.EventListeners.Core.SEND
*
* @!event retry(response)
* Triggered when a request failed and might need to be retried or redirected.
* If the response is retryable, the listener should set the
* `response.error.retryable` property to `true`, and optionally set
* `response.error.retryCount` to the millisecond delay for the next attempt.
* In the case of a redirect, `response.error.redirect` should be set to
* `true` with `retryCount` set to an optional delay on the next request.
*
* If a listener decides that a request should not be retried,
* it should set both `retryable` and `redirect` to false.
*
* Note that a retryable error will be retried at most
* {AWS.Config.maxRetries} times (based on the service object's config).
* Similarly, a request that is redirected will only redirect at most
* {AWS.Config.maxRedirects} times.
*
* @param (see AWS.Request~send)
* @context (see AWS.Request~send)
* @example Adding a custom retry for a 404 response
* request.on('retry', function(response) {
* // this resource is not yet available, wait 10 seconds to get it again
* if (response.httpResponse.statusCode === 404 && response.error) {
* response.error.retryable = true; // retry this error
* response.error.retryCount = 10000; // wait 10 seconds
* }
* });
*
* @!group Data Parsing Events
*
* @!event extractError(response)
* Triggered on all non-2xx requests so that listeners can extract
* error details from the response body. Listeners to this event
* should set the `response.error` property.
* @param (see AWS.Request~send)
* @context (see AWS.Request~send)
*
* @!event extractData(response)
* Triggered in successful requests to allow listeners to
* de-serialize the response body into `response.data`.
* @param (see AWS.Request~send)
* @context (see AWS.Request~send)
*
* @!group Completion Events
*
* @!event success(response)
* Triggered when the request completed successfully.
* `response.data` will contain the response data and
* `response.error` will be null.
* @param (see AWS.Request~send)
* @context (see AWS.Request~send)
*
* @!event error(error, response)
* Triggered when an error occurs at any point during the
* request. `response.error` will contain details about the error
* that occurred. `response.data` will be null.
* @param error [Error] the error object containing details about
* the error that occurred.
* @param (see AWS.Request~send)
* @context (see AWS.Request~send)
*
* @!event complete(response)
* Triggered whenever a request cycle completes. `response.error`
* should be checked, since the request may have failed.
* @param (see AWS.Request~send)
* @context (see AWS.Request~send)
*
* @!group HTTP Events
*
* @!event httpHeaders(statusCode, headers, response)
* Triggered when headers are sent by the remote server
* @param statusCode [Integer] the HTTP response code
* @param headers [map<String,String>] the response headers
* @param (see AWS.Request~send)
* @context (see AWS.Request~send)
*
* @!event httpData(chunk, response)
* Triggered when data is sent by the remote server
* @param chunk [Buffer] the buffer data containing the next data chunk
* from the server
* @param (see AWS.Request~send)
* @context (see AWS.Request~send)
* @see AWS.EventListeners.Core.HTTP_DATA
*
* @!event httpUploadProgress(progress, response)
* Triggered when the HTTP request has uploaded more data
* @param progress [map] An object containing the `loaded` and `total` bytes
* of the request.
* @param (see AWS.Request~send)
* @context (see AWS.Request~send)
* @note This event will not be emitted in Node.js 0.8.x.
*
* @!event httpDownloadProgress(progress, response)
* Triggered when the HTTP request has downloaded more data
* @param progress [map] An object containing the `loaded` and `total` bytes
* of the request.
* @param (see AWS.Request~send)
* @context (see AWS.Request~send)
* @note This event will not be emitted in Node.js 0.8.x.
*
* @!event httpError(error, response)
* Triggered when the HTTP request failed
* @param error [Error] the error object that was thrown
* @param (see AWS.Request~send)
* @context (see AWS.Request~send)
*
* @!event httpDone(response)
* Triggered when the server is finished sending data
* @param (see AWS.Request~send)
* @context (see AWS.Request~send)
*
* @see AWS.Response
*/
AWS.Request = inherit({
/**
* Creates a request for an operation on a given service with
* a set of input parameters.
*
* @param service [AWS.Service] the service to perform the operation on
* @param operation [String] the operation to perform on the service
* @param params [Object] parameters to send to the operation.
* See the operation's documentation for the format of the
* parameters.
*/
constructor: function Request(service, operation, params) {
var endpoint = service.endpoint;
var region = service.config.region;
var customUserAgent = service.config.customUserAgent;
// global endpoints sign as us-east-1
if (service.isGlobalEndpoint) region = 'us-east-1';
this.domain = domain && domain.active;
this.service = service;
this.operation = operation;
this.params = params || {};
this.httpRequest = new AWS.HttpRequest(endpoint, region, customUserAgent);
this.startTime = AWS.util.date.getDate();
this.response = new AWS.Response(this);
this._asm = new AcceptorStateMachine(fsm.states, 'validate');
this._haltHandlersOnError = false;
AWS.SequentialExecutor.call(this);
this.emit = this.emitEvent;
},
/**
* @!group Sending a Request
*/
/**
* @overload send(callback = null)
* Sends the request object.
*
* @callback callback function(err, data)
* If a callback is supplied, it is called when a response is returned
* from the service.
* @context [AWS.Request] the request object being sent.
* @param err [Error] the error object returned from the request.
* Set to `null` if the request is successful.
* @param data [Object] the de-serialized data returned from
* the request. Set to `null` if a request error occurs.
* @example Sending a request with a callback
* request = s3.putObject({Bucket: 'bucket', Key: 'key'});
* request.send(function(err, data) { console.log(err, data); });
* @example Sending a request with no callback (using event handlers)
* request = s3.putObject({Bucket: 'bucket', Key: 'key'});
* request.on('complete', function(response) { ... }); // register a callback
* request.send();
*/
send: function send(callback) {
if (callback) {
this.on('complete', function (resp) {
callback.call(resp, resp.error, resp.data);
});
}
this.runTo();
return this.response;
},
/**
* @!method promise()
* Returns a 'thenable' promise.
*
* Two callbacks can be provided to the `then` method on the returned promise.
* The first callback will be called if the promise is fulfilled, and the second
* callback will be called if the promise is rejected.
* @callback fulfilledCallback function(data)
* Called if the promise is fulfilled.
* @param data [Object] the de-serialized data returned from the request.
* @callback rejectedCallback function(error)
* Called if the promise is rejected.
* @param error [Error] the error object returned from the request.
* @return [Promise] A promise that represents the state of the request.
* @example Sending a request using promises.
* var request = s3.putObject({Bucket: 'bucket', Key: 'key'});
* var result = request.promise();
* result.then(function(data) { ... }, function(error) { ... });
*/
/**
* @api private
*/
build: function build(callback) {
return this.runTo('send', callback);
},
/**
* @api private
*/
runTo: function runTo(state, done) {
this._asm.runTo(state, done, this);
return this;
},
/**
* Aborts a request, emitting the error and complete events.
*
* @!macro nobrowser
* @example Aborting a request after sending
* var params = {
* Bucket: 'bucket', Key: 'key',
* Body: new Buffer(1024 * 1024 * 5) // 5MB payload
* };
* var request = s3.putObject(params);
* request.send(function (err, data) {
* if (err) console.log("Error:", err.code, err.message);
* else console.log(data);
* });
*
* // abort request in 1 second
* setTimeout(request.abort.bind(request), 1000);
*
* // prints "Error: RequestAbortedError Request aborted by user"
* @return [AWS.Request] the same request object, for chaining.
* @since v1.4.0
*/
abort: function abort() {
this.removeAllListeners('validateResponse');
this.removeAllListeners('extractError');
this.on('validateResponse', function addAbortedError(resp) {
resp.error = AWS.util.error(new Error('Request aborted by user'), {
code: 'RequestAbortedError', retryable: false
});
});
if (this.httpRequest.stream) { // abort HTTP stream
this.httpRequest.stream.abort();
if (this.httpRequest._abortCallback) {
this.httpRequest._abortCallback();
} else {
this.removeAllListeners('send'); // haven't sent yet, so let's not
}
}
return this;
},
/**
* Iterates over each page of results given a pageable request, calling
* the provided callback with each page of data. After all pages have been
* retrieved, the callback is called with `null` data.
*
* @note This operation can generate multiple requests to a service.
* @example Iterating over multiple pages of objects in an S3 bucket
* var pages = 1;
* s3.listObjects().eachPage(function(err, data) {
* if (err) return;
* console.log("Page", pages++);
* console.log(data);
* });
* @example Iterating over multiple pages with an asynchronous callback
* s3.listObjects(params).eachPage(function(err, data, done) {
* doSomethingAsyncAndOrExpensive(function() {
* // The next page of results isn't fetched until done is called
* done();
* });
* });
* @callback callback function(err, data, [doneCallback])
* Called with each page of resulting data from the request. If the
* optional `doneCallback` is provided in the function, it must be called
* when the callback is complete.
*
* @param err [Error] an error object, if an error occurred.
* @param data [Object] a single page of response data. If there is no
* more data, this object will be `null`.
* @param doneCallback [Function] an optional done callback. If this
* argument is defined in the function declaration, it should be called
* when the next page is ready to be retrieved. This is useful for
* controlling serial pagination across asynchronous operations.
* @return [Boolean] if the callback returns `false`, pagination will
* stop.
*
* @see AWS.Request.eachItem
* @see AWS.Response.nextPage
* @since v1.4.0
*/
eachPage: function eachPage(callback) {
// Make all callbacks async-ish
callback = AWS.util.fn.makeAsync(callback, 3);
function wrappedCallback(response) {
callback.call(response, response.error, response.data, function (result) {
if (result === false) return;
if (response.hasNextPage()) {
response.nextPage().on('complete', wrappedCallback).send();
} else {
callback.call(response, null, null, AWS.util.fn.noop);
}
});
}
this.on('complete', wrappedCallback).send();
},
/**
* Enumerates over individual items of a request, paging the responses if
* necessary.
*
* @api experimental
* @since v1.4.0
*/
eachItem: function eachItem(callback) {
var self = this;
function wrappedCallback(err, data) {
if (err) return callback(err, null);
if (data === null) return callback(null, null);
var config = self.service.paginationConfig(self.operation);
var resultKey = config.resultKey;
if (Array.isArray(resultKey)) resultKey = resultKey[0];
var items = jmespath.search(data, resultKey);
var continueIteration = true;
AWS.util.arrayEach(items, function(item) {
continueIteration = callback(null, item);
if (continueIteration === false) {
return AWS.util.abort;
}
});
return continueIteration;
}
this.eachPage(wrappedCallback);
},
/**
* @return [Boolean] whether the operation can return multiple pages of
* response data.
* @see AWS.Response.eachPage
* @since v1.4.0
*/
isPageable: function isPageable() {
return this.service.paginationConfig(this.operation) ? true : false;
},
/**
* Converts the request object into a readable stream that
* can be read from or piped into a writable stream.
*
* @note The data read from a readable stream contains only
* the raw HTTP body contents.
* @example Manually reading from a stream
* request.createReadStream().on('data', function(data) {
* console.log("Got data:", data.toString());
* });
* @example Piping a request body into a file
* var out = fs.createWriteStream('/path/to/outfile.jpg');
* s3.service.getObject(params).createReadStream().pipe(out);
* @return [Stream] the readable stream object that can be piped
* or read from (by registering 'data' event listeners).
* @!macro nobrowser
*/
createReadStream: function createReadStream() {
var streams = AWS.util.nodeRequire('stream');
var req = this;
var stream = null;
if (AWS.HttpClient.streamsApiVersion === 2) {
stream = new streams.PassThrough();
req.send();
} else {
stream = new streams.Stream();
stream.readable = true;
stream.sent = false;
stream.on('newListener', function(event) {
if (!stream.sent && event === 'data') {
stream.sent = true;
process.nextTick(function() { req.send(); });
}
});
}
this.on('httpHeaders', function streamHeaders(statusCode, headers, resp) {
if (statusCode < 300) {
req.removeListener('httpData', AWS.EventListeners.Core.HTTP_DATA);
req.removeListener('httpError', AWS.EventListeners.Core.HTTP_ERROR);
req.on('httpError', function streamHttpError(error) {
resp.error = error;
resp.error.retryable = false;
});
var shouldCheckContentLength = false;
var expectedLen;
if (req.httpRequest.method !== 'HEAD') {
expectedLen = parseInt(headers['content-length'], 10);
}
if (expectedLen !== undefined && !isNaN(expectedLen) && expectedLen >= 0) {
shouldCheckContentLength = true;
var receivedLen = 0;
}
var checkContentLengthAndEmit = function checkContentLengthAndEmit() {
if (shouldCheckContentLength && receivedLen !== expectedLen) {
stream.emit('error', AWS.util.error(
new Error('Stream content length mismatch. Received ' +
receivedLen + ' of ' + expectedLen + ' bytes.'),
{ code: 'StreamContentLengthMismatch' }
));
} else if (AWS.HttpClient.streamsApiVersion === 2) {
stream.end();
} else {
stream.emit('end')
}
}
var httpStream = resp.httpResponse.createUnbufferedStream();
if (AWS.HttpClient.streamsApiVersion === 2) {
if (shouldCheckContentLength) {
var lengthAccumulator = new streams.PassThrough();
lengthAccumulator._write = function(chunk) {
if (chunk && chunk.length) {
receivedLen += chunk.length;
}
return streams.PassThrough.prototype._write.apply(this, arguments);
};
lengthAccumulator.on('end', checkContentLengthAndEmit);
httpStream.pipe(lengthAccumulator).pipe(stream, { end: false });
} else {
httpStream.pipe(stream);
}
} else {
if (shouldCheckContentLength) {
httpStream.on('data', function(arg) {
if (arg && arg.length) {
receivedLen += arg.length;
}
});
}
httpStream.on('data', function(arg) {
stream.emit('data', arg);
});
httpStream.on('end', checkContentLengthAndEmit);
}
httpStream.on('error', function(err) {
shouldCheckContentLength = false;
stream.emit('error', err);
});
}
});
this.on('error', function(err) {
stream.emit('error', err);
});
return stream;
},
/**
* @param [Array,Response] args This should be the response object,
* or an array of args to send to the event.
* @api private
*/
emitEvent: function emit(eventName, args, done) {
if (typeof args === 'function') { done = args; args = null; }
if (!done) done = function() { };
if (!args) args = this.eventParameters(eventName, this.response);
var origEmit = AWS.SequentialExecutor.prototype.emit;
origEmit.call(this, eventName, args, function (err) {
if (err) this.response.error = err;
done.call(this, err);
});
},
/**
* @api private
*/
eventParameters: function eventParameters(eventName) {
switch (eventName) {
case 'restart':
case 'validate':
case 'sign':
case 'build':
case 'afterValidate':
case 'afterBuild':
return [this];
case 'error':
return [this.response.error, this.response];
default:
return [this.response];
}
},
/**
* @api private
*/
presign: function presign(expires, callback) {
if (!callback && typeof expires === 'function') {
callback = expires;
expires = null;
}
return new AWS.Signers.Presign().sign(this.toGet(), expires, callback);
},
/**
* @api private
*/
isPresigned: function isPresigned() {
return Object.prototype.hasOwnProperty.call(this.httpRequest.headers, 'presigned-expires');
},
/**
* @api private
*/
toUnauthenticated: function toUnauthenticated() {
this.removeListener('validate', AWS.EventListeners.Core.VALIDATE_CREDENTIALS);
this.removeListener('sign', AWS.EventListeners.Core.SIGN);
return this;
},
/**
* @api private
*/
toGet: function toGet() {
if (this.service.api.protocol === 'query' ||
this.service.api.protocol === 'ec2') {
this.removeListener('build', this.buildAsGet);
this.addListener('build', this.buildAsGet);
}
return this;
},
/**
* @api private
*/
buildAsGet: function buildAsGet(request) {
request.httpRequest.method = 'GET';
request.httpRequest.path = request.service.endpoint.path +
'?' + request.httpRequest.body;
request.httpRequest.body = '';
// don't need these headers on a GET request
delete request.httpRequest.headers['Content-Length'];
delete request.httpRequest.headers['Content-Type'];
},
/**
* @api private
*/
haltHandlersOnError: function haltHandlersOnError() {
this._haltHandlersOnError = true;
}
});
AWS.util.addPromisesToRequests(AWS.Request);
AWS.util.mixin(AWS.Request, AWS.SequentialExecutor);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | 1 1 1 1 1 1 1 1 | /**
* Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You
* may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
var AWS = require('./core');
var inherit = AWS.util.inherit;
var jmespath = require('jmespath');
/**
* @api private
*/
function CHECK_ACCEPTORS(resp) {
var waiter = resp.request._waiter;
var acceptors = waiter.config.acceptors;
var acceptorMatched = false;
var state = 'retry';
acceptors.forEach(function(acceptor) {
if (!acceptorMatched) {
var matcher = waiter.matchers[acceptor.matcher];
if (matcher && matcher(resp, acceptor.expected, acceptor.argument)) {
acceptorMatched = true;
state = acceptor.state;
}
}
});
if (!acceptorMatched && resp.error) state = 'failure';
if (state === 'success') {
waiter.setSuccess(resp);
} else {
waiter.setError(resp, state === 'retry');
}
}
/**
* @api private
*/
AWS.ResourceWaiter = inherit({
/**
* Waits for a given state on a service object
* @param service [Service] the service object to wait on
* @param state [String] the state (defined in waiter configuration) to wait
* for.
* @example Create a waiter for running EC2 instances
* var ec2 = new AWS.EC2;
* var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning');
*/
constructor: function constructor(service, state) {
this.service = service;
this.state = state;
this.loadWaiterConfig(this.state);
},
service: null,
state: null,
config: null,
matchers: {
path: function(resp, expected, argument) {
var result = jmespath.search(resp.data, argument);
return jmespath.strictDeepEqual(result,expected);
},
pathAll: function(resp, expected, argument) {
var results = jmespath.search(resp.data, argument);
if (!Array.isArray(results)) results = [results];
var numResults = results.length;
if (!numResults) return false;
for (var ind = 0 ; ind < numResults; ind++) {
if (!jmespath.strictDeepEqual(results[ind], expected)) {
return false;
}
}
return true;
},
pathAny: function(resp, expected, argument) {
var results = jmespath.search(resp.data, argument);
if (!Array.isArray(results)) results = [results];
var numResults = results.length;
for (var ind = 0 ; ind < numResults; ind++) {
if (jmespath.strictDeepEqual(results[ind], expected)) {
return true;
}
}
return false;
},
status: function(resp, expected) {
var statusCode = resp.httpResponse.statusCode;
return (typeof statusCode === 'number') && (statusCode === expected);
},
error: function(resp, expected) {
if (typeof expected === 'string' && resp.error) {
return expected === resp.error.code;
}
// if expected is not string, can be boolean indicating presence of error
return expected === !!resp.error;
}
},
listeners: new AWS.SequentialExecutor().addNamedListeners(function(add) {
add('RETRY_CHECK', 'retry', function(resp) {
var waiter = resp.request._waiter;
if (resp.error && resp.error.code === 'ResourceNotReady') {
resp.error.retryDelay = (waiter.config.delay || 0) * 1000;
}
});
add('CHECK_OUTPUT', 'extractData', CHECK_ACCEPTORS);
add('CHECK_ERROR', 'extractError', CHECK_ACCEPTORS);
}),
/**
* @return [AWS.Request]
*/
wait: function wait(params, callback) {
if (typeof params === 'function') {
callback = params; params = undefined;
}
var request = this.service.makeRequest(this.config.operation, params);
request._waiter = this;
request.response.maxRetries = this.config.maxAttempts;
request.addListeners(this.listeners);
if (callback) request.send(callback);
return request;
},
setSuccess: function setSuccess(resp) {
resp.error = null;
resp.data = resp.data || {};
resp.request.removeAllListeners('extractData');
},
setError: function setError(resp, retryable) {
resp.data = null;
resp.error = AWS.util.error(resp.error || new Error(), {
code: 'ResourceNotReady',
message: 'Resource is not in the state ' + this.state,
retryable: retryable
});
},
/**
* Loads waiter configuration from API configuration
*
* @api private
*/
loadWaiterConfig: function loadWaiterConfig(state) {
if (!this.service.api.waiters[state]) {
throw new AWS.util.error(new Error(), {
code: 'StateNotFoundError',
message: 'State ' + state + ' not found.'
});
}
this.config = this.service.api.waiters[state];
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | 1 1 1 1 | var AWS = require('./core');
var inherit = AWS.util.inherit;
var jmespath = require('jmespath');
/**
* This class encapsulates the response information
* from a service request operation sent through {AWS.Request}.
* The response object has two main properties for getting information
* back from a request:
*
* ## The `data` property
*
* The `response.data` property contains the serialized object data
* retrieved from the service request. For instance, for an
* Amazon DynamoDB `listTables` method call, the response data might
* look like:
*
* ```
* > resp.data
* { TableNames:
* [ 'table1', 'table2', ... ] }
* ```
*
* The `data` property can be null if an error occurs (see below).
*
* ## The `error` property
*
* In the event of a service error (or transfer error), the
* `response.error` property will be filled with the given
* error data in the form:
*
* ```
* { code: 'SHORT_UNIQUE_ERROR_CODE',
* message: 'Some human readable error message' }
* ```
*
* In the case of an error, the `data` property will be `null`.
* Note that if you handle events that can be in a failure state,
* you should always check whether `response.error` is set
* before attempting to access the `response.data` property.
*
* @!attribute data
* @readonly
* @!group Data Properties
* @note Inside of a {AWS.Request~httpData} event, this
* property contains a single raw packet instead of the
* full de-serialized service response.
* @return [Object] the de-serialized response data
* from the service.
*
* @!attribute error
* An structure containing information about a service
* or networking error.
* @readonly
* @!group Data Properties
* @note This attribute is only filled if a service or
* networking error occurs.
* @return [Error]
* * code [String] a unique short code representing the
* error that was emitted.
* * message [String] a longer human readable error message
* * retryable [Boolean] whether the error message is
* retryable.
* * statusCode [Numeric] in the case of a request that reached the service,
* this value contains the response status code.
* * time [Date] the date time object when the error occurred.
* * hostname [String] set when a networking error occurs to easily
* identify the endpoint of the request.
* * region [String] set when a networking error occurs to easily
* identify the region of the request.
*
* @!attribute requestId
* @readonly
* @!group Data Properties
* @return [String] the unique request ID associated with the response.
* Log this value when debugging requests for AWS support.
*
* @!attribute retryCount
* @readonly
* @!group Operation Properties
* @return [Integer] the number of retries that were
* attempted before the request was completed.
*
* @!attribute redirectCount
* @readonly
* @!group Operation Properties
* @return [Integer] the number of redirects that were
* followed before the request was completed.
*
* @!attribute httpResponse
* @readonly
* @!group HTTP Properties
* @return [AWS.HttpResponse] the raw HTTP response object
* containing the response headers and body information
* from the server.
*
* @see AWS.Request
*/
AWS.Response = inherit({
/**
* @api private
*/
constructor: function Response(request) {
this.request = request;
this.data = null;
this.error = null;
this.retryCount = 0;
this.redirectCount = 0;
this.httpResponse = new AWS.HttpResponse();
if (request) {
this.maxRetries = request.service.numRetries();
this.maxRedirects = request.service.config.maxRedirects;
}
},
/**
* Creates a new request for the next page of response data, calling the
* callback with the page data if a callback is provided.
*
* @callback callback function(err, data)
* Called when a page of data is returned from the next request.
*
* @param err [Error] an error object, if an error occurred in the request
* @param data [Object] the next page of data, or null, if there are no
* more pages left.
* @return [AWS.Request] the request object for the next page of data
* @return [null] if no callback is provided and there are no pages left
* to retrieve.
* @since v1.4.0
*/
nextPage: function nextPage(callback) {
var config;
var service = this.request.service;
var operation = this.request.operation;
try {
config = service.paginationConfig(operation, true);
} catch (e) { this.error = e; }
if (!this.hasNextPage()) {
if (callback) callback(this.error, null);
else if (this.error) throw this.error;
return null;
}
var params = AWS.util.copy(this.request.params);
if (!this.nextPageTokens) {
return callback ? callback(null, null) : null;
} else {
var inputTokens = config.inputToken;
if (typeof inputTokens === 'string') inputTokens = [inputTokens];
for (var i = 0; i < inputTokens.length; i++) {
params[inputTokens[i]] = this.nextPageTokens[i];
}
return service.makeRequest(this.request.operation, params, callback);
}
},
/**
* @return [Boolean] whether more pages of data can be returned by further
* requests
* @since v1.4.0
*/
hasNextPage: function hasNextPage() {
this.cacheNextPageTokens();
if (this.nextPageTokens) return true;
if (this.nextPageTokens === undefined) return undefined;
else return false;
},
/**
* @api private
*/
cacheNextPageTokens: function cacheNextPageTokens() {
if (Object.prototype.hasOwnProperty.call(this, 'nextPageTokens')) return this.nextPageTokens;
this.nextPageTokens = undefined;
var config = this.request.service.paginationConfig(this.request.operation);
if (!config) return this.nextPageTokens;
this.nextPageTokens = null;
if (config.moreResults) {
if (!jmespath.search(this.data, config.moreResults)) {
return this.nextPageTokens;
}
}
var exprs = config.outputToken;
if (typeof exprs === 'string') exprs = [exprs];
AWS.util.arrayEach.call(this, exprs, function (expr) {
var output = jmespath.search(this.data, expr);
if (output) {
this.nextPageTokens = this.nextPageTokens || [];
this.nextPageTokens.push(output);
}
});
return this.nextPageTokens;
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | 1 1 10 42 9 33 42 1 42 42 42 5 5 9 9 37 5 9 1 1 | var AWS = require('./core');
/**
* @api private
* @!method on(eventName, callback)
* Registers an event listener callback for the event given by `eventName`.
* Parameters passed to the callback function depend on the individual event
* being triggered. See the event documentation for those parameters.
*
* @param eventName [String] the event name to register the listener for
* @param callback [Function] the listener callback function
* @return [AWS.SequentialExecutor] the same object for chaining
*/
AWS.SequentialExecutor = AWS.util.inherit({
constructor: function SequentialExecutor() {
this._events = {};
},
/**
* @api private
*/
listeners: function listeners(eventName) {
return this._events[eventName] ? this._events[eventName].slice(0) : [];
},
on: function on(eventName, listener) {
if (this._events[eventName]) {
this._events[eventName].push(listener);
} else {
this._events[eventName] = [listener];
}
return this;
},
/**
* @api private
*/
onAsync: function onAsync(eventName, listener) {
listener._isAsync = true;
return this.on(eventName, listener);
},
removeListener: function removeListener(eventName, listener) {
var listeners = this._events[eventName];
if (listeners) {
var length = listeners.length;
var position = -1;
for (var i = 0; i < length; ++i) {
if (listeners[i] === listener) {
position = i;
}
}
if (position > -1) {
listeners.splice(position, 1);
}
}
return this;
},
removeAllListeners: function removeAllListeners(eventName) {
if (eventName) {
delete this._events[eventName];
} else {
this._events = {};
}
return this;
},
/**
* @api private
*/
emit: function emit(eventName, eventArgs, doneCallback) {
if (!doneCallback) doneCallback = function() { };
var listeners = this.listeners(eventName);
var count = listeners.length;
this.callListeners(listeners, eventArgs, doneCallback);
return count > 0;
},
/**
* @api private
*/
callListeners: function callListeners(listeners, args, doneCallback, prevError) {
var self = this;
var error = prevError || null;
function callNextListener(err) {
if (err) {
error = AWS.util.error(error || new Error(), err);
if (self._haltHandlersOnError) {
return doneCallback.call(self, error);
}
}
self.callListeners(listeners, args, doneCallback, error);
}
while (listeners.length > 0) {
var listener = listeners.shift();
if (listener._isAsync) { // asynchronous listener
listener.apply(self, args.concat([callNextListener]));
return; // stop here, callNextListener will continue
} else { // synchronous listener
try {
listener.apply(self, args);
} catch (err) {
error = AWS.util.error(error || new Error(), err);
}
if (error && self._haltHandlersOnError) {
doneCallback.call(self, error);
return;
}
}
}
doneCallback.call(self, error);
},
/**
* Adds or copies a set of listeners from another list of
* listeners or SequentialExecutor object.
*
* @param listeners [map<String,Array<Function>>, AWS.SequentialExecutor]
* a list of events and callbacks, or an event emitter object
* containing listeners to add to this emitter object.
* @return [AWS.SequentialExecutor] the emitter object, for chaining.
* @example Adding listeners from a map of listeners
* emitter.addListeners({
* event1: [function() { ... }, function() { ... }],
* event2: [function() { ... }]
* });
* emitter.emit('event1'); // emitter has event1
* emitter.emit('event2'); // emitter has event2
* @example Adding listeners from another emitter object
* var emitter1 = new AWS.SequentialExecutor();
* emitter1.on('event1', function() { ... });
* emitter1.on('event2', function() { ... });
* var emitter2 = new AWS.SequentialExecutor();
* emitter2.addListeners(emitter1);
* emitter2.emit('event1'); // emitter2 has event1
* emitter2.emit('event2'); // emitter2 has event2
*/
addListeners: function addListeners(listeners) {
var self = this;
// extract listeners if parameter is an SequentialExecutor object
if (listeners._events) listeners = listeners._events;
AWS.util.each(listeners, function(event, callbacks) {
if (typeof callbacks === 'function') callbacks = [callbacks];
AWS.util.arrayEach(callbacks, function(callback) {
self.on(event, callback);
});
});
return self;
},
/**
* Registers an event with {on} and saves the callback handle function
* as a property on the emitter object using a given `name`.
*
* @param name [String] the property name to set on this object containing
* the callback function handle so that the listener can be removed in
* the future.
* @param (see on)
* @return (see on)
* @example Adding a named listener DATA_CALLBACK
* var listener = function() { doSomething(); };
* emitter.addNamedListener('DATA_CALLBACK', 'data', listener);
*
* // the following prints: true
* console.log(emitter.DATA_CALLBACK == listener);
*/
addNamedListener: function addNamedListener(name, eventName, callback) {
this[name] = callback;
this.addListener(eventName, callback);
return this;
},
/**
* @api private
*/
addNamedAsyncListener: function addNamedAsyncListener(name, eventName, callback) {
callback._isAsync = true;
return this.addNamedListener(name, eventName, callback);
},
/**
* Helper method to add a set of named listeners using
* {addNamedListener}. The callback contains a parameter
* with a handle to the `addNamedListener` method.
*
* @callback callback function(add)
* The callback function is called immediately in order to provide
* the `add` function to the block. This simplifies the addition of
* a large group of named listeners.
* @param add [Function] the {addNamedListener} function to call
* when registering listeners.
* @example Adding a set of named listeners
* emitter.addNamedListeners(function(add) {
* add('DATA_CALLBACK', 'data', function() { ... });
* add('OTHER', 'otherEvent', function() { ... });
* add('LAST', 'lastEvent', function() { ... });
* });
*
* // these properties are now set:
* emitter.DATA_CALLBACK;
* emitter.OTHER;
* emitter.LAST;
*/
addNamedListeners: function addNamedListeners(callback) {
var self = this;
callback(
function() {
self.addNamedListener.apply(self, arguments);
},
function() {
self.addNamedAsyncListener.apply(self, arguments);
}
);
return this;
}
});
/**
* {on} is the prefered method.
* @api private
*/
AWS.SequentialExecutor.prototype.addListener = AWS.SequentialExecutor.prototype.on;
module.exports = AWS.SequentialExecutor;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 | 1 1 1 1 1 1 1 74 74 74 74 74 74 74 74 74 74 74 107 107 74 1 | var AWS = require('./core');
var Api = require('./model/api');
var regionConfig = require('./region_config');
var inherit = AWS.util.inherit;
var clientCount = 0;
/**
* The service class representing an AWS service.
*
* @abstract
*
* @!attribute apiVersions
* @return [Array<String>] the list of API versions supported by this service.
* @readonly
*/
AWS.Service = inherit({
/**
* Create a new service object with a configuration object
*
* @param config [map] a map of configuration options
*/
constructor: function Service(config) {
if (!this.loadServiceClass) {
throw AWS.util.error(new Error(),
'Service must be constructed with `new\' operator');
}
var ServiceClass = this.loadServiceClass(config || {});
if (ServiceClass) {
var originalConfig = AWS.util.copy(config);
var svc = new ServiceClass(config);
Object.defineProperty(svc, '_originalConfig', {
get: function() { return originalConfig; },
enumerable: false,
configurable: true
});
svc._clientId = ++clientCount;
return svc;
}
this.initialize(config);
},
/**
* @api private
*/
initialize: function initialize(config) {
var svcConfig = AWS.config[this.serviceIdentifier];
this.config = new AWS.Config(AWS.config);
if (svcConfig) this.config.update(svcConfig, true);
if (config) this.config.update(config, true);
this.validateService();
if (!this.config.endpoint) regionConfig(this);
this.config.endpoint = this.endpointFromTemplate(this.config.endpoint);
this.setEndpoint(this.config.endpoint);
},
/**
* @api private
*/
validateService: function validateService() {
},
/**
* @api private
*/
loadServiceClass: function loadServiceClass(serviceConfig) {
var config = serviceConfig;
if (!AWS.util.isEmpty(this.api)) {
return null;
} else if (config.apiConfig) {
return AWS.Service.defineServiceApi(this.constructor, config.apiConfig);
} else if (!this.constructor.services) {
return null;
} else {
config = new AWS.Config(AWS.config);
config.update(serviceConfig, true);
var version = config.apiVersions[this.constructor.serviceIdentifier];
version = version || config.apiVersion;
return this.getLatestServiceClass(version);
}
},
/**
* @api private
*/
getLatestServiceClass: function getLatestServiceClass(version) {
version = this.getLatestServiceVersion(version);
if (this.constructor.services[version] === null) {
AWS.Service.defineServiceApi(this.constructor, version);
}
return this.constructor.services[version];
},
/**
* @api private
*/
getLatestServiceVersion: function getLatestServiceVersion(version) {
if (!this.constructor.services || this.constructor.services.length === 0) {
throw new Error('No services defined on ' +
this.constructor.serviceIdentifier);
}
if (!version) {
version = 'latest';
} else if (AWS.util.isType(version, Date)) {
version = AWS.util.date.iso8601(version).split('T')[0];
}
if (Object.hasOwnProperty(this.constructor.services, version)) {
return version;
}
var keys = Object.keys(this.constructor.services).sort();
var selectedVersion = null;
for (var i = keys.length - 1; i >= 0; i--) {
// versions that end in "*" are not available on disk and can be
// skipped, so do not choose these as selectedVersions
if (keys[i][keys[i].length - 1] !== '*') {
selectedVersion = keys[i];
}
if (keys[i].substr(0, 10) <= version) {
return selectedVersion;
}
}
throw new Error('Could not find ' + this.constructor.serviceIdentifier +
' API to satisfy version constraint `' + version + '\'');
},
/**
* @api private
*/
api: {},
/**
* @api private
*/
defaultRetryCount: 3,
/**
* Calls an operation on a service with the given input parameters.
*
* @param operation [String] the name of the operation to call on the service.
* @param params [map] a map of input options for the operation
* @callback callback function(err, data)
* If a callback is supplied, it is called when a response is returned
* from the service.
* @param err [Error] the error object returned from the request.
* Set to `null` if the request is successful.
* @param data [Object] the de-serialized data returned from
* the request. Set to `null` if a request error occurs.
*/
makeRequest: function makeRequest(operation, params, callback) {
if (typeof params === 'function') {
callback = params;
params = null;
}
params = params || {};
if (this.config.params) { // copy only toplevel bound params
var rules = this.api.operations[operation];
if (rules) {
params = AWS.util.copy(params);
AWS.util.each(this.config.params, function(key, value) {
if (rules.input.members[key]) {
if (params[key] === undefined || params[key] === null) {
params[key] = value;
}
}
});
}
}
var request = new AWS.Request(this, operation, params);
this.addAllRequestListeners(request);
if (callback) request.send(callback);
return request;
},
/**
* Calls an operation on a service with the given input parameters, without
* any authentication data. This method is useful for "public" API operations.
*
* @param operation [String] the name of the operation to call on the service.
* @param params [map] a map of input options for the operation
* @callback callback function(err, data)
* If a callback is supplied, it is called when a response is returned
* from the service.
* @param err [Error] the error object returned from the request.
* Set to `null` if the request is successful.
* @param data [Object] the de-serialized data returned from
* the request. Set to `null` if a request error occurs.
*/
makeUnauthenticatedRequest: function makeUnauthenticatedRequest(operation, params, callback) {
if (typeof params === 'function') {
callback = params;
params = {};
}
var request = this.makeRequest(operation, params).toUnauthenticated();
return callback ? request.send(callback) : request;
},
/**
* Waits for a given state
*
* @param state [String] the state on the service to wait for
* @param params [map] a map of parameters to pass with each request
* @callback callback function(err, data)
* If a callback is supplied, it is called when a response is returned
* from the service.
* @param err [Error] the error object returned from the request.
* Set to `null` if the request is successful.
* @param data [Object] the de-serialized data returned from
* the request. Set to `null` if a request error occurs.
*/
waitFor: function waitFor(state, params, callback) {
var waiter = new AWS.ResourceWaiter(this, state);
return waiter.wait(params, callback);
},
/**
* @api private
*/
addAllRequestListeners: function addAllRequestListeners(request) {
var list = [AWS.events, AWS.EventListeners.Core, this.serviceInterface(),
AWS.EventListeners.CorePost];
for (var i = 0; i < list.length; i++) {
if (list[i]) request.addListeners(list[i]);
}
// disable parameter validation
if (!this.config.paramValidation) {
request.removeListener('validate',
AWS.EventListeners.Core.VALIDATE_PARAMETERS);
}
if (this.config.logger) { // add logging events
request.addListeners(AWS.EventListeners.Logger);
}
this.setupRequestListeners(request);
},
/**
* Override this method to setup any custom request listeners for each
* new request to the service.
*
* @abstract
*/
setupRequestListeners: function setupRequestListeners() {
},
/**
* Gets the signer class for a given request
* @api private
*/
getSignerClass: function getSignerClass() {
var version;
if (this.config.signatureVersion) {
version = this.config.signatureVersion;
} else {
version = this.api.signatureVersion;
}
return AWS.Signers.RequestSigner.getVersion(version);
},
/**
* @api private
*/
serviceInterface: function serviceInterface() {
switch (this.api.protocol) {
case 'ec2': return AWS.EventListeners.Query;
case 'query': return AWS.EventListeners.Query;
case 'json': return AWS.EventListeners.Json;
case 'rest-json': return AWS.EventListeners.RestJson;
case 'rest-xml': return AWS.EventListeners.RestXml;
}
if (this.api.protocol) {
throw new Error('Invalid service `protocol\' ' +
this.api.protocol + ' in API config');
}
},
/**
* @api private
*/
successfulResponse: function successfulResponse(resp) {
return resp.httpResponse.statusCode < 300;
},
/**
* How many times a failed request should be retried before giving up.
* the defaultRetryCount can be overriden by service classes.
*
* @api private
*/
numRetries: function numRetries() {
if (this.config.maxRetries !== undefined) {
return this.config.maxRetries;
} else {
return this.defaultRetryCount;
}
},
/**
* @api private
*/
retryDelays: function retryDelays(retryCount) {
var retryDelayOptions = this.config.retryDelayOptions || {};
var customBackoff = retryDelayOptions.customBackoff || null;
if (typeof customBackoff === 'function') {
return customBackoff(retryCount);
}
var base = retryDelayOptions.base || 30;
var delay = Math.random() * (Math.pow(2, retryCount) * base);
return delay;
},
/**
* @api private
*/
retryableError: function retryableError(error) {
if (this.networkingError(error)) return true;
if (this.expiredCredentialsError(error)) return true;
if (this.throttledError(error)) return true;
if (error.statusCode >= 500) return true;
return false;
},
/**
* @api private
*/
networkingError: function networkingError(error) {
return error.code === 'NetworkingError';
},
/**
* @api private
*/
expiredCredentialsError: function expiredCredentialsError(error) {
// TODO : this only handles *one* of the expired credential codes
return (error.code === 'ExpiredTokenException');
},
/**
* @api private
*/
clockSkewError: function clockSkewError(error) {
switch (error.code) {
case 'RequestTimeTooSkewed':
case 'RequestExpired':
case 'InvalidSignatureException':
case 'SignatureDoesNotMatch':
case 'AuthFailure':
case 'RequestInTheFuture':
return true;
default: return false;
}
},
/**
* @api private
*/
throttledError: function throttledError(error) {
// this logic varies between services
switch (error.code) {
case 'ProvisionedThroughputExceededException':
case 'Throttling':
case 'ThrottlingException':
case 'RequestLimitExceeded':
case 'RequestThrottled':
return true;
default:
return false;
}
},
/**
* @api private
*/
endpointFromTemplate: function endpointFromTemplate(endpoint) {
if (typeof endpoint !== 'string') return endpoint;
var e = endpoint;
e = e.replace(/\{service\}/g, this.api.endpointPrefix);
e = e.replace(/\{region\}/g, this.config.region);
e = e.replace(/\{scheme\}/g, this.config.sslEnabled ? 'https' : 'http');
return e;
},
/**
* @api private
*/
setEndpoint: function setEndpoint(endpoint) {
this.endpoint = new AWS.Endpoint(endpoint, this.config);
},
/**
* @api private
*/
paginationConfig: function paginationConfig(operation, throwException) {
var paginator = this.api.operations[operation].paginator;
if (!paginator) {
if (throwException) {
var e = new Error();
throw AWS.util.error(e, 'No pagination configuration for ' + operation);
}
return null;
}
return paginator;
}
});
AWS.util.update(AWS.Service, {
/**
* Adds one method for each operation described in the api configuration
*
* @api private
*/
defineMethods: function defineMethods(svc) {
AWS.util.each(svc.prototype.api.operations, function iterator(method) {
if (svc.prototype[method]) return;
var operation = svc.prototype.api.operations[method];
if (operation.authtype === 'none') {
svc.prototype[method] = function (params, callback) {
return this.makeUnauthenticatedRequest(method, params, callback);
};
} else {
svc.prototype[method] = function (params, callback) {
return this.makeRequest(method, params, callback);
};
}
});
},
/**
* Defines a new Service class using a service identifier and list of versions
* including an optional set of features (functions) to apply to the class
* prototype.
*
* @param serviceIdentifier [String] the identifier for the service
* @param versions [Array<String>] a list of versions that work with this
* service
* @param features [Object] an object to attach to the prototype
* @return [Class<Service>] the service class defined by this function.
*/
defineService: function defineService(serviceIdentifier, versions, features) {
AWS.Service._serviceMap[serviceIdentifier] = true;
Iif (!Array.isArray(versions)) {
features = versions;
versions = [];
}
var svc = inherit(AWS.Service, features || {});
Eif (typeof serviceIdentifier === 'string') {
AWS.Service.addVersions(svc, versions);
var identifier = svc.serviceIdentifier || serviceIdentifier;
svc.serviceIdentifier = identifier;
} else { // defineService called with an API
svc.prototype.api = serviceIdentifier;
AWS.Service.defineMethods(svc);
}
return svc;
},
/**
* @api private
*/
addVersions: function addVersions(svc, versions) {
Iif (!Array.isArray(versions)) versions = [versions];
svc.services = svc.services || {};
for (var i = 0; i < versions.length; i++) {
Eif (svc.services[versions[i]] === undefined) {
svc.services[versions[i]] = null;
}
}
svc.apiVersions = Object.keys(svc.services).sort();
},
/**
* @api private
*/
defineServiceApi: function defineServiceApi(superclass, version, apiConfig) {
var svc = inherit(superclass, {
serviceIdentifier: superclass.serviceIdentifier
});
function setApi(api) {
if (api.isApi) {
svc.prototype.api = api;
} else {
svc.prototype.api = new Api(api);
}
}
if (typeof version === 'string') {
if (apiConfig) {
setApi(apiConfig);
} else {
try {
setApi(AWS.apiLoader(superclass.serviceIdentifier, version));
} catch (err) {
throw AWS.util.error(err, {
message: 'Could not find API configuration ' +
superclass.serviceIdentifier + '-' + version
});
}
}
if (!Object.prototype.hasOwnProperty.call(superclass.services, version)) {
superclass.apiVersions = superclass.apiVersions.concat(version).sort();
}
superclass.services[version] = svc;
} else {
setApi(version);
}
AWS.Service.defineMethods(svc);
return svc;
},
/**
* @api private
*/
hasService: function(identifier) {
return Object.prototype.hasOwnProperty.call(AWS.Service._serviceMap, identifier);
},
/**
* @api private
*/
_serviceMap: {}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 1 1 1 1 1 74 74 74 74 74 | var fs = require('fs');
var path = require('path');
var AWS = require('./core');
var apis = require('./api_loader');
// define services using map
apis.services.forEach(function(identifier) {
var name = apis.serviceName(identifier);
var versions = apis.serviceVersions(identifier);
AWS[name] = AWS.Service.defineService(identifier, versions);
// load any customizations from lib/services/<svcidentifier>.js
var svcFile = path.join(__dirname, 'services', identifier + '.js');
if (fs.existsSync(svcFile)) require('./services/' + identifier);
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 1 1 1 1 1 14 14 14 14 14 1 | function AcceptorStateMachine(states, state) {
this.currentState = state || null;
this.states = states || {};
}
AcceptorStateMachine.prototype.runTo = function runTo(finalState, done, bindObject, inputError) {
if (typeof finalState === 'function') {
inputError = bindObject; bindObject = done;
done = finalState; finalState = null;
}
var self = this;
var state = self.states[self.currentState];
state.fn.call(bindObject || self, inputError, function(err) {
if (err) {
if (state.fail) self.currentState = state.fail;
else return done ? done.call(bindObject, err) : null;
} else {
if (state.accept) self.currentState = state.accept;
else return done ? done.call(bindObject) : null;
}
if (self.currentState === finalState) {
return done ? done.call(bindObject, err) : null;
}
self.runTo(finalState, done, bindObject, err);
});
};
AcceptorStateMachine.prototype.addState = function addState(name, acceptState, failState, fn) {
Iif (typeof acceptState === 'function') {
fn = acceptState; acceptState = null; failState = null;
} else Iif (typeof failState === 'function') {
fn = failState; failState = null;
}
if (!this.currentState) this.currentState = name;
this.states[name] = { accept: acceptState, fail: failState, fn: fn };
return this;
};
module.exports = AcceptorStateMachine;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 | 1 1 1 1 9 6 6 2 2 6 6 6 131 492 492 492 4 4 4 4 129 442 129 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 109 109 20 20 20 89 89 89 109 81 109 109 109 109 2 2 2 26 26 24 2 4 4 4 1 1 1 1 1 1 | /* eslint guard-for-in:0 */
var cryptoLib = require('crypto');
var Buffer = require('buffer').Buffer;
var AWS;
/**
* A set of utility methods for use with the AWS SDK.
*
* @!attribute abort
* Return this value from an iterator function {each} or {arrayEach}
* to break out of the iteration.
* @example Breaking out of an iterator function
* AWS.util.each({a: 1, b: 2, c: 3}, function(key, value) {
* if (key == 'b') return AWS.util.abort;
* });
* @see each
* @see arrayEach
* @api private
*/
var util = {
engine: function engine() {
if (util.isBrowser() && typeof navigator !== 'undefined') {
return navigator.userAgent;
} else {
return process.platform + '/' + process.version;
}
},
userAgent: function userAgent() {
var name = util.isBrowser() ? 'js' : 'nodejs';
var agent = 'aws-sdk-' + name + '/' + require('./core').VERSION;
if (name === 'nodejs') agent += ' ' + util.engine();
return agent;
},
isBrowser: function isBrowser() { return process && process.browser; },
isNode: function isNode() { return !util.isBrowser(); },
nodeRequire: function nodeRequire(module) {
Eif (util.isNode()) return require(module);
},
multiRequire: function multiRequire(module1, module2) {
return require(util.isNode() ? module1 : module2);
},
uriEscape: function uriEscape(string) {
var output = encodeURIComponent(string);
output = output.replace(/[^A-Za-z0-9_.~\-%]+/g, escape);
// AWS percent-encodes some extra non-standard characters in a URI
output = output.replace(/[*]/g, function(ch) {
return '%' + ch.charCodeAt(0).toString(16).toUpperCase();
});
return output;
},
uriEscapePath: function uriEscapePath(string) {
var parts = [];
util.arrayEach(string.split('/'), function (part) {
parts.push(util.uriEscape(part));
});
return parts.join('/');
},
urlParse: function urlParse(url) {
return require('url').parse(url);
},
urlFormat: function urlFormat(url) {
return require('url').format(url);
},
queryStringParse: function queryStringParse(qs) {
return require('querystring').parse(qs);
},
queryParamsToString: function queryParamsToString(params) {
var items = [];
var escape = util.uriEscape;
var sortedKeys = Object.keys(params).sort();
util.arrayEach(sortedKeys, function(name) {
var value = params[name];
var ename = escape(name);
var result = ename + '=';
if (Array.isArray(value)) {
var vals = [];
util.arrayEach(value, function(item) { vals.push(escape(item)); });
result = ename + '=' + vals.sort().join('&' + ename + '=');
} else if (value !== undefined && value !== null) {
result = ename + '=' + escape(value);
}
items.push(result);
});
return items.join('&');
},
readFileSync: function readFileSync(path) {
Iif (util.isBrowser()) return null;
return util.nodeRequire('fs').readFileSync(path, 'utf-8');
},
base64: {
encode: function encode64(string) {
return new Buffer(string).toString('base64');
},
decode: function decode64(string) {
return new Buffer(string, 'base64');
}
},
Buffer: Buffer,
buffer: {
toStream: function toStream(buffer) {
if (!util.Buffer.isBuffer(buffer)) buffer = new util.Buffer(buffer);
var readable = new (util.nodeRequire('stream').Readable)();
var pos = 0;
readable._read = function(size) {
if (pos >= buffer.length) return readable.push(null);
var end = pos + size;
if (end > buffer.length) end = buffer.length;
readable.push(buffer.slice(pos, end));
pos = end;
};
return readable;
},
/**
* Concatenates a list of Buffer objects.
*/
concat: function(buffers) {
var length = 0,
offset = 0,
buffer = null, i;
for (i = 0; i < buffers.length; i++) {
length += buffers[i].length;
}
buffer = new Buffer(length);
for (i = 0; i < buffers.length; i++) {
buffers[i].copy(buffer, offset);
offset += buffers[i].length;
}
return buffer;
}
},
string: {
byteLength: function byteLength(string) {
if (string === null || string === undefined) return 0;
if (typeof string === 'string') string = new Buffer(string);
if (typeof string.byteLength === 'number') {
return string.byteLength;
} else if (typeof string.length === 'number') {
return string.length;
} else if (typeof string.size === 'number') {
return string.size;
} else if (typeof string.path === 'string') {
return util.nodeRequire('fs').lstatSync(string.path).size;
} else {
throw util.error(new Error('Cannot determine length of ' + string),
{ object: string });
}
},
upperFirst: function upperFirst(string) {
return string[0].toUpperCase() + string.substr(1);
},
lowerFirst: function lowerFirst(string) {
return string[0].toLowerCase() + string.substr(1);
}
},
ini: {
parse: function string(ini) {
var currentSection, map = {};
util.arrayEach(ini.split(/\r?\n/), function(line) {
line = line.split(/(^|\s)[;#]/)[0]; // remove comments
var section = line.match(/^\s*\[([^\[\]]+)\]\s*$/);
if (section) {
currentSection = section[1];
} else if (currentSection) {
var item = line.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/);
if (item) {
map[currentSection] = map[currentSection] || {};
map[currentSection][item[1]] = item[2];
}
}
});
return map;
}
},
fn: {
noop: function() {},
/**
* Turn a synchronous function into as "async" function by making it call
* a callback. The underlying function is called with all but the last argument,
* which is treated as the callback. The callback is passed passed a first argument
* of null on success to mimick standard node callbacks.
*/
makeAsync: function makeAsync(fn, expectedArgs) {
if (expectedArgs && expectedArgs <= fn.length) {
return fn;
}
return function() {
var args = Array.prototype.slice.call(arguments, 0);
var callback = args.pop();
var result = fn.apply(null, args);
callback(result);
};
}
},
/**
* Date and time utility functions.
*/
date: {
/**
* @return [Date] the current JavaScript date object. Since all
* AWS services rely on this date object, you can override
* this function to provide a special time value to AWS service
* requests.
*/
getDate: function getDate() {
if (!AWS) AWS = require('./core');
Iif (AWS.config.systemClockOffset) { // use offset when non-zero
return new Date(new Date().getTime() + AWS.config.systemClockOffset);
} else {
return new Date();
}
},
/**
* @return [String] the date in ISO-8601 format
*/
iso8601: function iso8601(date) {
if (date === undefined) { date = util.date.getDate(); }
return date.toISOString().replace(/\.\d{3}Z$/, 'Z');
},
/**
* @return [String] the date in RFC 822 format
*/
rfc822: function rfc822(date) {
if (date === undefined) { date = util.date.getDate(); }
return date.toUTCString();
},
/**
* @return [Integer] the UNIX timestamp value for the current time
*/
unixTimestamp: function unixTimestamp(date) {
if (date === undefined) { date = util.date.getDate(); }
return date.getTime() / 1000;
},
/**
* @param [String,number,Date] date
* @return [Date]
*/
from: function format(date) {
if (typeof date === 'number') {
return new Date(date * 1000); // unix timestamp
} else {
return new Date(date);
}
},
/**
* Given a Date or date-like value, this function formats the
* date into a string of the requested value.
* @param [String,number,Date] date
* @param [String] formatter Valid formats are:
# * 'iso8601'
# * 'rfc822'
# * 'unixTimestamp'
* @return [String]
*/
format: function format(date, formatter) {
if (!formatter) formatter = 'iso8601';
return util.date[formatter](util.date.from(date));
},
parseTimestamp: function parseTimestamp(value) {
if (typeof value === 'number') { // unix timestamp (number)
return new Date(value * 1000);
} else if (value.match(/^\d+$/)) { // unix timestamp
return new Date(value * 1000);
} else if (value.match(/^\d{4}/)) { // iso8601
return new Date(value);
} else if (value.match(/^\w{3},/)) { // rfc822
return new Date(value);
} else {
throw util.error(
new Error('unhandled timestamp format: ' + value),
{code: 'TimestampParserError'});
}
}
},
crypto: {
crc32Table: [
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419,
0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4,
0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07,
0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856,
0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3,
0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A,
0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599,
0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190,
0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E,
0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED,
0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3,
0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,
0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010,
0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17,
0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6,
0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344,
0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A,
0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1,
0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,
0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE,
0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C,
0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B,
0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1,
0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278,
0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66,
0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,
0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8,
0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B,
0x2D02EF8D],
crc32: function crc32(data) {
var tbl = util.crypto.crc32Table;
var crc = 0 ^ -1;
if (typeof data === 'string') {
data = new Buffer(data);
}
for (var i = 0; i < data.length; i++) {
var code = data.readUInt8(i);
crc = (crc >>> 8) ^ tbl[(crc ^ code) & 0xFF];
}
return (crc ^ -1) >>> 0;
},
hmac: function hmac(key, string, digest, fn) {
if (!digest) digest = 'binary';
if (digest === 'buffer') { digest = undefined; }
if (!fn) fn = 'sha256';
if (typeof string === 'string') string = new Buffer(string);
return cryptoLib.createHmac(fn, key).update(string).digest(digest);
},
md5: function md5(data, digest, callback) {
return util.crypto.hash('md5', data, digest, callback);
},
sha256: function sha256(data, digest, callback) {
return util.crypto.hash('sha256', data, digest, callback);
},
hash: function(algorithm, data, digest, callback) {
var hash = util.crypto.createHash(algorithm);
if (!digest) { digest = 'binary'; }
if (digest === 'buffer') { digest = undefined; }
if (typeof data === 'string') data = new Buffer(data);
var sliceFn = util.arraySliceFn(data);
var isBuffer = Buffer.isBuffer(data);
//Identifying objects with an ArrayBuffer as buffers
if (util.isBrowser() && typeof ArrayBuffer !== 'undefined' && data && data.buffer instanceof ArrayBuffer) isBuffer = true;
if (callback && typeof data === 'object' &&
typeof data.on === 'function' && !isBuffer) {
data.on('data', function(chunk) { hash.update(chunk); });
data.on('error', function(err) { callback(err); });
data.on('end', function() { callback(null, hash.digest(digest)); });
} else if (callback && sliceFn && !isBuffer &&
typeof FileReader !== 'undefined') {
// this might be a File/Blob
var index = 0, size = 1024 * 512;
var reader = new FileReader();
reader.onerror = function() {
callback(new Error('Failed to read data.'));
};
reader.onload = function() {
var buf = new Buffer(new Uint8Array(reader.result));
hash.update(buf);
index += buf.length;
reader._continueReading();
};
reader._continueReading = function() {
if (index >= data.size) {
callback(null, hash.digest(digest));
return;
}
var back = index + size;
if (back > data.size) back = data.size;
reader.readAsArrayBuffer(sliceFn.call(data, index, back));
};
reader._continueReading();
} else {
if (util.isBrowser() && typeof data === 'object' && !isBuffer) {
data = new Buffer(new Uint8Array(data));
}
var out = hash.update(data).digest(digest);
if (callback) callback(null, out);
return out;
}
},
toHex: function toHex(data) {
var out = [];
for (var i = 0; i < data.length; i++) {
out.push(('0' + data.charCodeAt(i).toString(16)).substr(-2, 2));
}
return out.join('');
},
createHash: function createHash(algorithm) {
return cryptoLib.createHash(algorithm);
}
},
/** @!ignore */
/* Abort constant */
abort: {},
each: function each(object, iterFunction) {
for (var key in object) {
Eif (Object.prototype.hasOwnProperty.call(object, key)) {
var ret = iterFunction.call(this, key, object[key]);
Iif (ret === util.abort) break;
}
}
},
arrayEach: function arrayEach(array, iterFunction) {
for (var idx in array) {
Eif (Object.prototype.hasOwnProperty.call(array, idx)) {
var ret = iterFunction.call(this, array[idx], parseInt(idx, 10));
Iif (ret === util.abort) break;
}
}
},
update: function update(obj1, obj2) {
util.each(obj2, function iterator(key, item) {
obj1[key] = item;
});
return obj1;
},
merge: function merge(obj1, obj2) {
return util.update(util.copy(obj1), obj2);
},
copy: function copy(object) {
if (object === null || object === undefined) return object;
var dupe = {};
// jshint forin:false
for (var key in object) {
dupe[key] = object[key];
}
return dupe;
},
isEmpty: function isEmpty(obj) {
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
return false;
}
}
return true;
},
arraySliceFn: function arraySliceFn(obj) {
var fn = obj.slice || obj.webkitSlice || obj.mozSlice;
return typeof fn === 'function' ? fn : null;
},
isType: function isType(obj, type) {
// handle cross-"frame" objects
if (typeof type === 'function') type = util.typeName(type);
return Object.prototype.toString.call(obj) === '[object ' + type + ']';
},
typeName: function typeName(type) {
if (Object.prototype.hasOwnProperty.call(type, 'name')) return type.name;
var str = type.toString();
var match = str.match(/^\s*function (.+)\(/);
return match ? match[1] : str;
},
error: function error(err, options) {
var originalError = null;
Eif (typeof err.message === 'string' && err.message !== '') {
Iif (typeof options === 'string' || (options && options.message)) {
originalError = util.copy(err);
originalError.message = err.message;
}
}
err.message = err.message || null;
Iif (typeof options === 'string') {
err.message = options;
} else Eif (typeof options === 'object' && options !== null) {
util.update(err, options);
Iif (options.message)
err.message = options.message;
Eif (options.code || options.name)
err.code = options.code || options.name;
Iif (options.stack)
err.stack = options.stack;
}
Eif (typeof Object.defineProperty === 'function') {
Object.defineProperty(err, 'name', {writable: true, enumerable: false});
Object.defineProperty(err, 'message', {enumerable: true});
}
err.name = options && options.name || err.name || err.code || 'Error';
err.time = new Date();
Iif (originalError) err.originalError = originalError;
return err;
},
/**
* @api private
*/
inherit: function inherit(klass, features) {
var newObject = null;
if (features === undefined) {
features = klass;
klass = Object;
newObject = {};
} else {
var ctor = function ConstructorWrapper() {};
ctor.prototype = klass.prototype;
newObject = new ctor();
}
// constructor not supplied, create pass-through ctor
if (features.constructor === Object) {
features.constructor = function() {
if (klass !== Object) {
return klass.apply(this, arguments);
}
};
}
features.constructor.prototype = newObject;
util.update(features.constructor.prototype, features);
features.constructor.__super__ = klass;
return features.constructor;
},
/**
* @api private
*/
mixin: function mixin() {
var klass = arguments[0];
for (var i = 1; i < arguments.length; i++) {
// jshint forin:false
for (var prop in arguments[i].prototype) {
var fn = arguments[i].prototype[prop];
if (prop !== 'constructor') {
klass.prototype[prop] = fn;
}
}
}
return klass;
},
/**
* @api private
*/
hideProperties: function hideProperties(obj, props) {
Iif (typeof Object.defineProperty !== 'function') return;
util.arrayEach(props, function (key) {
Object.defineProperty(obj, key, {
enumerable: false, writable: true, configurable: true });
});
},
/**
* @api private
*/
property: function property(obj, name, value, enumerable, isValue) {
var opts = {
configurable: true,
enumerable: enumerable !== undefined ? enumerable : true
};
if (typeof value === 'function' && !isValue) {
opts.get = value;
}
else {
opts.value = value; opts.writable = true;
}
Object.defineProperty(obj, name, opts);
},
/**
* @api private
*/
memoizedProperty: function memoizedProperty(obj, name, get, enumerable) {
var cachedValue = null;
// build enumerable attribute for each value with lazy accessor.
util.property(obj, name, function() {
if (cachedValue === null) {
cachedValue = get();
}
return cachedValue;
}, enumerable);
},
/**
* TODO Remove in major version revision
* This backfill populates response data without the
* top-level payload name.
*
* @api private
*/
hoistPayloadMember: function hoistPayloadMember(resp) {
var req = resp.request;
var operation = req.operation;
var output = req.service.api.operations[operation].output;
if (output.payload) {
var payloadMember = output.members[output.payload];
var responsePayload = resp.data[output.payload];
if (payloadMember.type === 'structure') {
util.each(responsePayload, function(key, value) {
util.property(resp.data, key, value, false);
});
}
}
},
/**
* Compute SHA-256 checksums of streams
*
* @api private
*/
computeSha256: function computeSha256(body, done) {
if (util.isNode()) {
var Stream = util.nodeRequire('stream').Stream;
var fs = util.nodeRequire('fs');
if (body instanceof Stream) {
if (typeof body.path === 'string') { // assume file object
var settings = {};
if (typeof body.start === 'number') {
settings.start = body.start;
}
if (typeof body.end === 'number') {
settings.end = body.end;
}
body = fs.createReadStream(body.path, settings);
} else { // TODO support other stream types
return done(new Error('Non-file stream objects are ' +
'not supported with SigV4'));
}
}
}
util.crypto.sha256(body, 'hex', function(err, sha) {
if (err) done(err);
else done(null, sha);
});
},
/**
* @api private
*/
isClockSkewed: function isClockSkewed(serverTime) {
if (serverTime) {
util.property(AWS.config, 'isClockSkewed',
Math.abs(new Date().getTime() - serverTime) >= 300000, false);
return AWS.config.isClockSkewed;
}
},
applyClockOffset: function applyClockOffset(serverTime) {
if (serverTime)
AWS.config.systemClockOffset = serverTime - new Date().getTime();
},
/**
* @api private
*/
extractRequestId: function extractRequestId(resp) {
var requestId = resp.httpResponse.headers['x-amz-request-id'] ||
resp.httpResponse.headers['x-amzn-requestid'];
if (!requestId && resp.data && resp.data.ResponseMetadata) {
requestId = resp.data.ResponseMetadata.RequestId;
}
if (requestId) {
resp.requestId = requestId;
}
if (resp.error) {
resp.error.requestId = requestId;
}
},
/**
* @api private
*/
addPromisesToRequests: function addPromisesToRequests(constructor, PromiseDependency) {
PromiseDependency = PromiseDependency || null;
Eif (!PromiseDependency && typeof Promise !== 'undefined') {
PromiseDependency = Promise;
}
Iif (typeof PromiseDependency !== 'function') {
delete constructor.prototype.promise;
return;
}
constructor.prototype.promise = function promise() {
var self = this;
return new PromiseDependency(function(resolve, reject) {
self.on('complete', function(resp) {
if (resp.error) {
reject(resp.error);
} else {
resolve(resp.data);
}
});
self.runTo();
});
}
},
/**
* @api private
*/
isDualstackAvailable: function isDualstackAvailable(service) {
if (!service) return false;
var metadata = require('../apis/metadata.json');
if (typeof service !== 'string') service = service.serviceIdentifier;
if (typeof service !== 'string' || !metadata.hasOwnProperty(service)) return false;
return !!metadata[service].dualstackAvailable;
}
};
module.exports = util;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| signer.js | 20% | (12 / 60) | 0% | (0 / 30) | 0% | (0 / 13) | 20% | (12 / 60) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | 1 1 1 1 1 1 1 1 1 1 1 1 | var crypto = require('crypto'),
url = require('url'),
AWS = require('../core'),
base64Encode = AWS.util.base64.encode,
inherit = AWS.util.inherit;
var queryEncode = function (string) {
var replacements = {
'+': '-',
'=': '_',
'/': '~'
};
return string.replace(/[\+=\/]/g, function (match) {
return replacements[match];
});
};
var signPolicy = function (policy, privateKey) {
var sign = crypto.createSign('RSA-SHA1');
sign.write(policy);
return queryEncode(sign.sign(privateKey, 'base64'))
};
var signWithCannedPolicy = function (url, expires, keyPairId, privateKey) {
var policy = JSON.stringify({
Statement: [
{
Resource: url,
Condition: { DateLessThan: { 'AWS:EpochTime': expires } }
}
]
});
return {
Expires: expires,
'Key-Pair-Id': keyPairId,
Signature: signPolicy(policy.toString(), privateKey)
};
};
var signWithCustomPolicy = function (policy, keyPairId, privateKey) {
policy = policy.replace(/\s/mg, policy);
return {
Policy: queryEncode(base64Encode(policy)),
'Key-Pair-Id': keyPairId,
Signature: signPolicy(policy, privateKey)
}
};
var determineScheme = function (url) {
var parts = url.split('://');
if (parts.length < 2) {
throw new Error('Invalid URL.');
}
return parts[0].replace('*', '');
};
var getRtmpUrl = function (rtmpUrl) {
var parsed = url.parse(rtmpUrl);
return parsed.path.replace(/^\//, '') + (parsed.hash || '');
};
var getResource = function (url) {
switch (determineScheme(url)) {
case 'http':
case 'https':
return url;
case 'rtmp':
return getRtmpUrl(url);
default:
throw new Error('Invalid URI scheme. Scheme must be one of'
+ ' http, https, or rtmp');
}
};
var handleError = function (err, callback) {
if (!callback || typeof callback !== 'function') {
throw err;
}
callback(err);
};
var handleSuccess = function (result, callback) {
if (!callback || typeof callback !== 'function') {
return result;
}
callback(null, result);
};
AWS.CloudFront.Signer = inherit({
/**
* A signer object can be used to generate signed URLs and cookies for granting
* access to content on restricted CloudFront distributions.
*
* @see http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html
*
* @param keyPairId [String] (Required) The ID of the CloudFront key pair
* being used.
* @param privateKey [String] (Required) A private key in RSA format.
*/
constructor: function Signer(keyPairId, privateKey) {
if (keyPairId === void 0 || privateKey === void 0) {
throw new Error('A key pair ID and private key are required');
}
this.keyPairId = keyPairId;
this.privateKey = privateKey;
},
/**
* Create a signed Amazon CloudFront Cookie.
*
* @param options [Object] The options to create a signed cookie.
* @option options url [String] The URL to which the signature will grant
* access. Required unless you pass in a full
* policy.
* @option options expires [Number] A Unix UTC timestamp indicating when the
* signature should expire. Required unless you
* pass in a full policy.
* @option options policy [String] A CloudFront JSON policy. Required unless
* you pass in a url and an expiry time.
*
* @param cb [Function] if a callback is provided, this function will
* pass the hash as the second parameter (after the error parameter) to
* the callback function.
*
* @return [Object] if called synchronously (with no callback), returns the
* signed cookie parameters.
* @return [null] nothing is returned if a callback is provided.
*/
getSignedCookie: function (options, cb) {
var signatureHash = 'policy' in options
? signWithCustomPolicy(options.policy, this.keyPairId, this.privateKey)
: signWithCannedPolicy(options.url, options.expires, this.keyPairId, this.privateKey);
var cookieHash = {};
for (var key in signatureHash) {
if (Object.prototype.hasOwnProperty.call(signatureHash, key)) {
cookieHash['CloudFront-' + key] = signatureHash[key];
}
}
return handleSuccess(cookieHash, cb);
},
/**
* Create a signed Amazon CloudFront URL.
*
* Keep in mind that URLs meant for use in media/flash players may have
* different requirements for URL formats (e.g. some require that the
* extension be removed, some require the file name to be prefixed
* - mp4:<path>, some require you to add "/cfx/st" into your URL).
*
* @param options [Object] The options to create a signed URL.
* @option options url [String] The URL to which the signature will grant
* access. Required.
* @option options expires [Number] A Unix UTC timestamp indicating when the
* signature should expire. Required unless you
* pass in a full policy.
* @option options policy [String] A CloudFront JSON policy. Required unless
* you pass in a url and an expiry time.
*
* @param cb [Function] if a callback is provided, this function will
* pass the URL as the second parameter (after the error parameter) to
* the callback function.
*
* @return [String] if called synchronously (with no callback), returns the
* signed URL.
* @return [null] nothing is returned if a callback is provided.
*/
getSignedUrl: function (options, cb) {
try {
var resource = getResource(options.url);
} catch (err) {
return handleError(err, cb);
}
var parsedUrl = url.parse(options.url, true),
signatureHash = Object.prototype.hasOwnProperty.call(options, 'policy')
? signWithCustomPolicy(options.policy, this.keyPairId, this.privateKey)
: signWithCannedPolicy(resource, options.expires, this.keyPairId, this.privateKey);
parsedUrl.search = null;
for (var key in signatureHash) {
if (Object.prototype.hasOwnProperty.call(signatureHash, key)) {
parsedUrl.query[key] = signatureHash[key];
}
}
try {
var signedUrl = determineScheme(options.url) === 'rtmp'
? getRtmpUrl(url.format(parsedUrl))
: url.format(parsedUrl);
} catch (err) {
return handleError(err, cb);
}
return handleSuccess(signedUrl, cb);
}
});
module.exports = AWS.CloudFront.Signer;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| cognito_identity_credentials.js | 4.44% | (4 / 90) | 3.51% | (2 / 57) | 5% | (1 / 20) | 4.49% | (4 / 89) | |
| credential_provider_chain.js | 84% | (21 / 25) | 73.33% | (11 / 15) | 100% | (4 / 4) | 84% | (21 / 25) | |
| ec2_metadata_credentials.js | 12.5% | (3 / 24) | 0% | (0 / 10) | 0% | (0 / 4) | 15% | (3 / 20) | |
| ecs_credentials.js | 4.08% | (2 / 49) | 0% | (0 / 26) | 0% | (0 / 11) | 4.76% | (2 / 42) | |
| environment_credentials.js | 68% | (17 / 25) | 57.14% | (8 / 14) | 75% | (3 / 4) | 76.19% | (16 / 21) | |
| file_system_credentials.js | 11.76% | (2 / 17) | 0% | (0 / 8) | 0% | (0 / 4) | 14.29% | (2 / 14) | |
| saml_credentials.js | 12.5% | (2 / 16) | 0% | (0 / 8) | 0% | (0 / 5) | 15.38% | (2 / 13) | |
| shared_ini_file_credentials.js | 29.69% | (19 / 64) | 20.45% | (9 / 44) | 57.14% | (4 / 7) | 30% | (18 / 60) | |
| temporary_credentials.js | 8.33% | (2 / 24) | 0% | (0 / 16) | 0% | (0 / 6) | 9.52% | (2 / 21) | |
| web_identity_credentials.js | 10% | (2 / 20) | 0% | (0 / 10) | 0% | (0 / 5) | 11.76% | (2 / 17) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 | 1 1 1 1 | var AWS = require('../core');
/**
* Represents credentials retrieved from STS Web Identity Federation using
* the Amazon Cognito Identity service.
*
* By default this provider gets credentials using the
* {AWS.CognitoIdentity.getCredentialsForIdentity} service operation, which
* requires either an `IdentityId` or an `IdentityPoolId` (Amazon Cognito
* Identity Pool ID), which is used to call {AWS.CognitoIdentity.getId} to
* obtain an `IdentityId`. If the identity or identity pool is not configured in
* the Amazon Cognito Console to use IAM roles with the appropriate permissions,
* then additionally a `RoleArn` is required containing the ARN of the IAM trust
* policy for the Amazon Cognito role that the user will log into. If a `RoleArn`
* is provided, then this provider gets credentials using the
* {AWS.STS.assumeRoleWithWebIdentity} service operation, after first getting an
* Open ID token from {AWS.CognitoIdentity.getOpenIdToken}.
*
* In addition, if this credential provider is used to provide authenticated
* login, the `Logins` map may be set to the tokens provided by the respective
* identity providers. See {constructor} for an example on creating a credentials
* object with proper property values.
*
* ## Refreshing Credentials from Identity Service
*
* In addition to AWS credentials expiring after a given amount of time, the
* login token from the identity provider will also expire. Once this token
* expires, it will not be usable to refresh AWS credentials, and another
* token will be needed. The SDK does not manage refreshing of the token value,
* but this can be done through a "refresh token" supported by most identity
* providers. Consult the documentation for the identity provider for refreshing
* tokens. Once the refreshed token is acquired, you should make sure to update
* this new token in the credentials object's {params} property. The following
* code will update the WebIdentityToken, assuming you have retrieved an updated
* token from the identity provider:
*
* ```javascript
* AWS.config.credentials.params.Logins['graph.facebook.com'] = updatedToken;
* ```
*
* Future calls to `credentials.refresh()` will now use the new token.
*
* @!attribute params
* @return [map] the map of params passed to
* {AWS.CognitoIdentity.getId},
* {AWS.CognitoIdentity.getOpenIdToken}, and
* {AWS.STS.assumeRoleWithWebIdentity}. To update the token, set the
* `params.WebIdentityToken` property.
* @!attribute data
* @return [map] the raw data response from the call to
* {AWS.CognitoIdentity.getCredentialsForIdentity}, or
* {AWS.STS.assumeRoleWithWebIdentity}. Use this if you want to get
* access to other properties from the response.
* @!attribute identityId
* @return [String] the Cognito ID returned by the last call to
* {AWS.CognitoIdentity.getOpenIdToken}. This ID represents the actual
* final resolved identity ID from Amazon Cognito.
*/
AWS.CognitoIdentityCredentials = AWS.util.inherit(AWS.Credentials, {
/**
* @api private
*/
localStorageKey: {
id: 'aws.cognito.identity-id.',
providers: 'aws.cognito.identity-providers.'
},
/**
* Creates a new credentials object.
* @example Creating a new credentials object
* AWS.config.credentials = new AWS.CognitoIdentityCredentials({
*
* // either IdentityPoolId or IdentityId is required
* // See the IdentityPoolId param for AWS.CognitoIdentity.getID (linked below)
* // See the IdentityId param for AWS.CognitoIdentity.getCredentialsForIdentity
* // or AWS.CognitoIdentity.getOpenIdToken (linked below)
* IdentityPoolId: 'us-east-1:1699ebc0-7900-4099-b910-2df94f52a030',
* IdentityId: 'us-east-1:128d0a74-c82f-4553-916d-90053e4a8b0f'
*
* // optional, only necessary when the identity pool is not configured
* // to use IAM roles in the Amazon Cognito Console
* // See the RoleArn param for AWS.STS.assumeRoleWithWebIdentity (linked below)
* RoleArn: 'arn:aws:iam::1234567890:role/MYAPP-CognitoIdentity',
*
* // optional tokens, used for authenticated login
* // See the Logins param for AWS.CognitoIdentity.getID (linked below)
* Logins: {
* 'graph.facebook.com': 'FBTOKEN',
* 'www.amazon.com': 'AMAZONTOKEN',
* 'accounts.google.com': 'GOOGLETOKEN',
* 'api.twitter.com': 'TWITTERTOKEN',
* 'www.digits.com': 'DIGITSTOKEN'
* },
*
* // optional name, defaults to web-identity
* // See the RoleSessionName param for AWS.STS.assumeRoleWithWebIdentity (linked below)
* RoleSessionName: 'web',
*
* // optional, only necessary when application runs in a browser
* // and multiple users are signed in at once, used for caching
* LoginId: 'example@gmail.com'
*
* });
* @see AWS.CognitoIdentity.getId
* @see AWS.CognitoIdentity.getCredentialsForIdentity
* @see AWS.STS.assumeRoleWithWebIdentity
* @see AWS.CognitoIdentity.getOpenIdToken
*/
constructor: function CognitoIdentityCredentials(params) {
AWS.Credentials.call(this);
this.expired = true;
this.params = params;
this.data = null;
this.identityId = null;
this.loadCachedId();
},
/**
* Refreshes credentials using {AWS.CognitoIdentity.getCredentialsForIdentity},
* or {AWS.STS.assumeRoleWithWebIdentity}.
*
* @callback callback function(err)
* Called when the STS service responds (or fails). When
* this callback is called with no error, it means that the credentials
* information has been loaded into the object (as the `accessKeyId`,
* `secretAccessKey`, and `sessionToken` properties).
* @param err [Error] if an error occurred, this value will be filled
* @see get
*/
refresh: function refresh(callback) {
var self = this;
self.createClients();
self.data = null;
self.identityId = null;
self.getId(function(err) {
if (!err) {
if (!self.params.RoleArn) {
self.getCredentialsForIdentity(callback);
} else {
self.getCredentialsFromSTS(callback);
}
} else {
self.clearIdOnNotAuthorized(err);
callback(err);
}
});
},
/**
* Clears the cached Cognito ID associated with the currently configured
* identity pool ID. Use this to manually invalidate your cache if
* the identity pool ID was deleted.
*/
clearCachedId: function clearCache() {
this.identityId = null;
delete this.params.IdentityId;
var poolId = this.params.IdentityPoolId;
var loginId = this.params.LoginId || '';
delete this.storage[this.localStorageKey.id + poolId + loginId];
delete this.storage[this.localStorageKey.providers + poolId + loginId];
},
/**
* @api private
*/
clearIdOnNotAuthorized: function clearIdOnNotAuthorized(err) {
var self = this;
if (err.code == 'NotAuthorizedException') {
self.clearCachedId();
}
},
/**
* Retrieves a Cognito ID, loading from cache if it was already retrieved
* on this device.
*
* @callback callback function(err, identityId)
* @param err [Error, null] an error object if the call failed or null if
* it succeeded.
* @param identityId [String, null] if successful, the callback will return
* the Cognito ID.
* @note If not loaded explicitly, the Cognito ID is loaded and stored in
* localStorage in the browser environment of a device.
* @api private
*/
getId: function getId(callback) {
var self = this;
if (typeof self.params.IdentityId === 'string') {
return callback(null, self.params.IdentityId);
}
self.cognito.getId(function(err, data) {
if (!err && data.IdentityId) {
self.params.IdentityId = data.IdentityId;
callback(null, data.IdentityId);
} else {
callback(err);
}
});
},
/**
* @api private
*/
loadCredentials: function loadCredentials(data, credentials) {
if (!data || !credentials) return;
credentials.expired = false;
credentials.accessKeyId = data.Credentials.AccessKeyId;
credentials.secretAccessKey = data.Credentials.SecretKey;
credentials.sessionToken = data.Credentials.SessionToken;
credentials.expireTime = data.Credentials.Expiration;
},
/**
* @api private
*/
getCredentialsForIdentity: function getCredentialsForIdentity(callback) {
var self = this;
self.cognito.getCredentialsForIdentity(function(err, data) {
if (!err) {
self.cacheId(data);
self.data = data;
self.loadCredentials(self.data, self);
} else {
self.clearIdOnNotAuthorized(err);
}
callback(err);
});
},
/**
* @api private
*/
getCredentialsFromSTS: function getCredentialsFromSTS(callback) {
var self = this;
self.cognito.getOpenIdToken(function(err, data) {
if (!err) {
self.cacheId(data);
self.params.WebIdentityToken = data.Token;
self.webIdentityCredentials.refresh(function(webErr) {
if (!webErr) {
self.data = self.webIdentityCredentials.data;
self.sts.credentialsFrom(self.data, self);
}
callback(webErr);
});
} else {
self.clearIdOnNotAuthorized(err);
callback(err);
}
});
},
/**
* @api private
*/
loadCachedId: function loadCachedId() {
var self = this;
// in the browser we source default IdentityId from localStorage
if (AWS.util.isBrowser() && !self.params.IdentityId) {
var id = self.getStorage('id');
if (id && self.params.Logins) {
var actualProviders = Object.keys(self.params.Logins);
var cachedProviders =
(self.getStorage('providers') || '').split(',');
// only load ID if at least one provider used this ID before
var intersect = cachedProviders.filter(function(n) {
return actualProviders.indexOf(n) !== -1;
});
if (intersect.length !== 0) {
self.params.IdentityId = id;
}
} else if (id) {
self.params.IdentityId = id;
}
}
},
/**
* @api private
*/
createClients: function() {
this.webIdentityCredentials = this.webIdentityCredentials ||
new AWS.WebIdentityCredentials(this.params);
this.cognito = this.cognito ||
new AWS.CognitoIdentity({params: this.params});
this.sts = this.sts || new AWS.STS();
},
/**
* @api private
*/
cacheId: function cacheId(data) {
this.identityId = data.IdentityId;
this.params.IdentityId = this.identityId;
// cache this IdentityId in browser localStorage if possible
if (AWS.util.isBrowser()) {
this.setStorage('id', data.IdentityId);
if (this.params.Logins) {
this.setStorage('providers', Object.keys(this.params.Logins).join(','));
}
}
},
/**
* @api private
*/
getStorage: function getStorage(key) {
return this.storage[this.localStorageKey[key] + this.params.IdentityPoolId + (this.params.LoginId || '')];
},
/**
* @api private
*/
setStorage: function setStorage(key, val) {
try {
this.storage[this.localStorageKey[key] + this.params.IdentityPoolId + (this.params.LoginId || '')] = val;
} catch (_) {}
},
/**
* @api private
*/
storage: (function() {
try {
return AWS.util.isBrowser() && window.localStorage !== null && typeof window.localStorage === 'object' ?
window.localStorage : {};
} catch (_) {
return {};
}
})()
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | 1 1 2 1 1 1 1 1 1 4 1 1 3 3 3 3 3 3 1 1 1 | var AWS = require('../core');
/**
* Creates a credential provider chain that searches for AWS credentials
* in a list of credential providers specified by the {providers} property.
*
* By default, the chain will use the {defaultProviders} to resolve credentials.
* These providers will look in the environment using the
* {AWS.EnvironmentCredentials} class with the 'AWS' and 'AMAZON' prefixes.
*
* ## Setting Providers
*
* Each provider in the {providers} list should be a function that returns
* a {AWS.Credentials} object, or a hardcoded credentials object. The function
* form allows for delayed execution of the credential construction.
*
* ## Resolving Credentials from a Chain
*
* Call {resolve} to return the first valid credential object that can be
* loaded by the provider chain.
*
* For example, to resolve a chain with a custom provider that checks a file
* on disk after the set of {defaultProviders}:
*
* ```javascript
* var diskProvider = new AWS.FileSystemCredentials('./creds.json');
* var chain = new AWS.CredentialProviderChain();
* chain.providers.push(diskProvider);
* chain.resolve();
* ```
*
* The above code will return the `diskProvider` object if the
* file contains credentials and the `defaultProviders` do not contain
* any credential settings.
*
* @!attribute providers
* @return [Array<AWS.Credentials, Function>]
* a list of credentials objects or functions that return credentials
* objects. If the provider is a function, the function will be
* executed lazily when the provider needs to be checked for valid
* credentials. By default, this object will be set to the
* {defaultProviders}.
* @see defaultProviders
*/
AWS.CredentialProviderChain = AWS.util.inherit(AWS.Credentials, {
/**
* Creates a new CredentialProviderChain with a default set of providers
* specified by {defaultProviders}.
*/
constructor: function CredentialProviderChain(providers) {
if (providers) {
this.providers = providers;
} else {
this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0);
}
},
/**
* Resolves the provider chain by searching for the first set of
* credentials in {providers}.
*
* @callback callback function(err, credentials)
* Called when the provider resolves the chain to a credentials object
* or null if no credentials can be found.
*
* @param err [Error] the error object returned if no credentials are
* found.
* @param credentials [AWS.Credentials] the credentials object resolved
* by the provider chain.
* @return [AWS.CredentialProviderChain] the provider, for chaining.
*/
resolve: function resolve(callback) {
Iif (this.providers.length === 0) {
callback(new Error('No providers'));
return this;
}
var index = 0;
var providers = this.providers.slice(0);
function resolveNext(err, creds) {
if ((!err && creds) || index === providers.length) {
callback(err, creds);
return;
}
var provider = providers[index++];
Eif (typeof provider === 'function') {
creds = provider.call();
} else {
creds = provider;
}
Eif (creds.get) {
creds.get(function(getErr) {
resolveNext(getErr, getErr ? null : creds);
});
} else {
resolveNext(null, creds);
}
}
resolveNext();
return this;
}
});
/**
* The default set of providers used by a vanilla CredentialProviderChain.
*
* In the browser:
*
* ```javascript
* AWS.CredentialProviderChain.defaultProviders = []
* ```
*
* In Node.js:
*
* ```javascript
* AWS.CredentialProviderChain.defaultProviders = [
* function () { return new AWS.EnvironmentCredentials('AWS'); },
* function () { return new AWS.EnvironmentCredentials('AMAZON'); },
* function () { return new AWS.SharedIniFileCredentials(); },
* function () {
* // if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set
* return new AWS.ECSCredentials();
* // else
* return new AWS.EC2MetadataCredentials();
* }
* ]
* ```
*/
AWS.CredentialProviderChain.defaultProviders = [];
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 1 1 1 | var AWS = require('../core');
require('../metadata_service');
/**
* Represents credentials received from the metadata service on an EC2 instance.
*
* By default, this class will connect to the metadata service using
* {AWS.MetadataService} and attempt to load any available credentials. If it
* can connect, and credentials are available, these will be used with zero
* configuration.
*
* This credentials class will timeout after 1 second of inactivity by default.
* If your requests to the EC2 metadata service are timing out, you can increase
* the value by configuring them directly:
*
* ```javascript
* AWS.config.credentials = new AWS.EC2MetadataCredentials({
* httpOptions: { timeout: 5000 } // 5 second timeout
* });
* ```
*
* @!macro nobrowser
*/
AWS.EC2MetadataCredentials = AWS.util.inherit(AWS.Credentials, {
constructor: function EC2MetadataCredentials(options) {
AWS.Credentials.call(this);
options = options ? AWS.util.copy(options) : {};
if (!options.httpOptions) options.httpOptions = {};
options.httpOptions = AWS.util.merge(
{timeout: this.defaultTimeout}, options.httpOptions);
this.metadataService = new AWS.MetadataService(options);
this.metadata = {};
},
/**
* @api private
*/
defaultTimeout: 1000,
/**
* Loads the credentials from the instance metadata service
*
* @callback callback function(err)
* Called when the instance metadata service responds (or fails). When
* this callback is called with no error, it means that the credentials
* information has been loaded into the object (as the `accessKeyId`,
* `secretAccessKey`, and `sessionToken` properties).
* @param err [Error] if an error occurred, this value will be filled
* @see get
*/
refresh: function refresh(callback) {
var self = this;
if (!callback) callback = function(err) { if (err) throw err; };
self.metadataService.loadCredentials(function (err, creds) {
if (!err) {
self.expired = false;
self.metadata = creds;
self.accessKeyId = creds.AccessKeyId;
self.secretAccessKey = creds.SecretAccessKey;
self.sessionToken = creds.Token;
self.expireTime = new Date(creds.Expiration);
}
callback(err);
});
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | 1 1 | var AWS = require('../core');
/**
* Represents credentials received from relative URI specified in the ECS container.
*
* This class will request refreshable credentials from the relative URI
* specified by the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI environment variable
* in the container. If valid credentials are returned in the response, these
* will be used with zero configuration.
*
* This credentials class will timeout after 1 second of inactivity by default.
* If your requests to the relative URI are timing out, you can increase
* the value by configuring them directly:
*
* ```javascript
* AWS.config.credentials = new AWS.ECSCredentials({
* httpOptions: { timeout: 5000 } // 5 second timeout
* });
* ```
*
* @!macro nobrowser
*/
AWS.ECSCredentials = AWS.util.inherit(AWS.Credentials, {
constructor: function ECSCredentials(options) {
AWS.Credentials.call(this);
options = options ? AWS.util.copy(options) : {};
if (!options.httpOptions) options.httpOptions = {};
options.httpOptions = AWS.util.merge(
this.httpOptions, options.httpOptions);
AWS.util.update(this, options);
},
/**
* @api private
*/
httpOptions: { timeout: 1000 },
/**
* @api private
*/
host: '169.254.170.2',
/**
* Sets the name of the ECS environment variable to check for relative URI
* If changed, please change the name in the documentation for defaultProvider
* in credential_provider_chain.js and in all tests in test/credentials.spec.coffee
*
* @api private
*/
environmentVar: 'AWS_CONTAINER_CREDENTIALS_RELATIVE_URI',
/**
* @api private
*/
getECSRelativeUri: function getECSRelativeUri() {
if (process && process.env) return process.env[this.environmentVar];
},
/**
* @api private
*/
credsFormatIsValid: function credsFormatIsValid(credData) {
return (!!credData.AccessKeyId && !!credData.SecretAccessKey &&
!!credData.Token && !!credData.Expiration);
},
/**
* @api private
*/
request: function request(path, callback) {
path = path || '/';
var data = '';
var http = AWS.HttpClient.getInstance();
var httpRequest = new AWS.HttpRequest('http://' + this.host + path);
httpRequest.method = 'GET';
httpRequest.headers.Accept = 'application/json';
var httpOptions = this.httpOptions;
process.nextTick(function() {
http.handleRequest(httpRequest, httpOptions, function(httpResponse) {
httpResponse.on('data', function(chunk) { data += chunk.toString(); });
httpResponse.on('end', function() { callback(null, data); });
}, callback);
});
},
/**
* Loads the credentials from the relative URI specified by container
*
* @callback callback function(err)
* Called when the request to the relative URI responds (or fails). When
* this callback is called with no error, it means that the credentials
* information has been loaded into the object (as the `accessKeyId`,
* `secretAccessKey`, `sessionToken`, and `expireTime` properties).
* @param err [Error] if an error occurred, this value will be filled
* @see get
*/
refresh: function refresh(callback) {
var self = this;
if (!callback) callback = function(err) { if (err) throw err; };
if (process === undefined) {
callback(AWS.util.error(
new Error('No process info available'),
{ code: 'ECSCredentialsProviderFailure' }
));
return;
}
var relativeUri = this.getECSRelativeUri();
if (relativeUri === undefined) {
callback(AWS.util.error(
new Error('Variable ' + this.environmentVar + ' not set.'),
{ code: 'ECSCredentialsProviderFailure' }
));
return;
}
this.request(relativeUri, function(err, data) {
if (!err) {
try {
var creds = JSON.parse(data);
if (self.credsFormatIsValid(creds)) {
self.expired = false;
self.accessKeyId = creds.AccessKeyId;
self.secretAccessKey = creds.SecretAccessKey;
self.sessionToken = creds.Token;
self.expireTime = new Date(creds.Expiration);
} else {
throw AWS.util.error(
new Error('Response data is not in valid format'),
{ code: 'ECSCredentialsProviderFailure' }
);
}
} catch (dataError) {
err = dataError;
}
}
callback(err);
});
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | 1 1 2 2 2 4 4 4 4 4 4 4 4 4 4 4 | var AWS = require('../core');
/**
* Represents credentials from the environment.
*
* By default, this class will look for the matching environment variables
* prefixed by a given {envPrefix}. The un-prefixed environment variable names
* for each credential value is listed below:
*
* ```javascript
* accessKeyId: ACCESS_KEY_ID
* secretAccessKey: SECRET_ACCESS_KEY
* sessionToken: SESSION_TOKEN
* ```
*
* With the default prefix of 'AWS', the environment variables would be:
*
* AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN
*
* @!attribute envPrefix
* @readonly
* @return [String] the prefix for the environment variable names excluding
* the separating underscore ('_').
*/
AWS.EnvironmentCredentials = AWS.util.inherit(AWS.Credentials, {
/**
* Creates a new EnvironmentCredentials class with a given variable
* prefix {envPrefix}. For example, to load credentials using the 'AWS'
* prefix:
*
* ```javascript
* var creds = new AWS.EnvironmentCredentials('AWS');
* creds.accessKeyId == 'AKID' // from AWS_ACCESS_KEY_ID env var
* ```
*
* @param envPrefix [String] the prefix to use (e.g., 'AWS') for environment
* variables. Do not include the separating underscore.
*/
constructor: function EnvironmentCredentials(envPrefix) {
AWS.Credentials.call(this);
this.envPrefix = envPrefix;
this.get(function() {});
},
/**
* Loads credentials from the environment using the prefixed
* environment variables.
*
* @callback callback function(err)
* Called after the (prefixed) ACCESS_KEY_ID, SECRET_ACCESS_KEY, and
* SESSION_TOKEN environment variables are read. When this callback is
* called with no error, it means that the credentials information has
* been loaded into the object (as the `accessKeyId`, `secretAccessKey`,
* and `sessionToken` properties).
* @param err [Error] if an error occurred, this value will be filled
* @see get
*/
refresh: function refresh(callback) {
Iif (!callback) callback = function(err) { if (err) throw err; };
Iif (!process || !process.env) {
callback(AWS.util.error(
new Error('No process info or environment variables available'),
{ code: 'EnvironmentCredentialsProviderFailure' }
));
return;
}
var keys = ['ACCESS_KEY_ID', 'SECRET_ACCESS_KEY', 'SESSION_TOKEN'];
var values = [];
for (var i = 0; i < keys.length; i++) {
var prefix = '';
Eif (this.envPrefix) prefix = this.envPrefix + '_';
values[i] = process.env[prefix + keys[i]];
Eif (!values[i] && keys[i] !== 'SESSION_TOKEN') {
callback(AWS.util.error(
new Error('Variable ' + prefix + keys[i] + ' not set.'),
{ code: 'EnvironmentCredentialsProviderFailure' }
));
return;
}
}
this.expired = false;
AWS.Credentials.apply(this, values);
callback();
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | 1 1 | var AWS = require('../core');
/**
* Represents credentials from a JSON file on disk.
* If the credentials expire, the SDK can {refresh} the credentials
* from the file.
*
* The format of the file should be similar to the options passed to
* {AWS.Config}:
*
* ```javascript
* {accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'optional'}
* ```
*
* @example Loading credentials from disk
* var creds = new AWS.FileSystemCredentials('./configuration.json');
* creds.accessKeyId == 'AKID'
*
* @!attribute filename
* @readonly
* @return [String] the path to the JSON file on disk containing the
* credentials.
* @!macro nobrowser
*/
AWS.FileSystemCredentials = AWS.util.inherit(AWS.Credentials, {
/**
* @overload AWS.FileSystemCredentials(filename)
* Creates a new FileSystemCredentials object from a filename
*
* @param filename [String] the path on disk to the JSON file to load.
*/
constructor: function FileSystemCredentials(filename) {
AWS.Credentials.call(this);
this.filename = filename;
this.get(function() {});
},
/**
* Loads the credentials from the {filename} on disk.
*
* @callback callback function(err)
* Called after the JSON file on disk is read and parsed. When this callback
* is called with no error, it means that the credentials information
* has been loaded into the object (as the `accessKeyId`, `secretAccessKey`,
* and `sessionToken` properties).
* @param err [Error] if an error occurred, this value will be filled
* @see get
*/
refresh: function refresh(callback) {
if (!callback) callback = function(err) { if (err) throw err; };
try {
var creds = JSON.parse(AWS.util.readFileSync(this.filename));
AWS.Credentials.call(this, creds);
if (!this.accessKeyId || !this.secretAccessKey) {
throw AWS.util.error(
new Error('Credentials not set in ' + this.filename),
{ code: 'FileSystemCredentialsProviderFailure' }
);
}
this.expired = false;
callback();
} catch (err) {
callback(err);
}
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | 1 1 | var AWS = require('../core');
/**
* Represents credentials retrieved from STS SAML support.
*
* By default this provider gets credentials using the
* {AWS.STS.assumeRoleWithSAML} service operation. This operation
* requires a `RoleArn` containing the ARN of the IAM trust policy for the
* application for which credentials will be given, as well as a `PrincipalArn`
* representing the ARN for the SAML identity provider. In addition, the
* `SAMLAssertion` must be set to the token provided by the identity
* provider. See {constructor} for an example on creating a credentials
* object with proper `RoleArn`, `PrincipalArn`, and `SAMLAssertion` values.
*
* ## Refreshing Credentials from Identity Service
*
* In addition to AWS credentials expiring after a given amount of time, the
* login token from the identity provider will also expire. Once this token
* expires, it will not be usable to refresh AWS credentials, and another
* token will be needed. The SDK does not manage refreshing of the token value,
* but this can be done through a "refresh token" supported by most identity
* providers. Consult the documentation for the identity provider for refreshing
* tokens. Once the refreshed token is acquired, you should make sure to update
* this new token in the credentials object's {params} property. The following
* code will update the SAMLAssertion, assuming you have retrieved an updated
* token from the identity provider:
*
* ```javascript
* AWS.config.credentials.params.SAMLAssertion = updatedToken;
* ```
*
* Future calls to `credentials.refresh()` will now use the new token.
*
* @!attribute params
* @return [map] the map of params passed to
* {AWS.STS.assumeRoleWithSAML}. To update the token, set the
* `params.SAMLAssertion` property.
*/
AWS.SAMLCredentials = AWS.util.inherit(AWS.Credentials, {
/**
* Creates a new credentials object.
* @param (see AWS.STS.assumeRoleWithSAML)
* @example Creating a new credentials object
* AWS.config.credentials = new AWS.SAMLCredentials({
* RoleArn: 'arn:aws:iam::1234567890:role/SAMLRole',
* PrincipalArn: 'arn:aws:iam::1234567890:role/SAMLPrincipal',
* SAMLAssertion: 'base64-token', // base64-encoded token from IdP
* });
* @see AWS.STS.assumeRoleWithSAML
*/
constructor: function SAMLCredentials(params) {
AWS.Credentials.call(this);
this.expired = true;
this.params = params;
},
/**
* Refreshes credentials using {AWS.STS.assumeRoleWithSAML}
*
* @callback callback function(err)
* Called when the STS service responds (or fails). When
* this callback is called with no error, it means that the credentials
* information has been loaded into the object (as the `accessKeyId`,
* `secretAccessKey`, and `sessionToken` properties).
* @param err [Error] if an error occurred, this value will be filled
* @see get
*/
refresh: function refresh(callback) {
var self = this;
self.createClients();
if (!callback) callback = function(err) { if (err) throw err; };
self.service.assumeRoleWithSAML(function (err, data) {
if (!err) {
self.service.credentialsFrom(data, self);
}
callback(err);
});
},
/**
* @api private
*/
createClients: function() {
this.service = this.service || new AWS.STS({params: this.params});
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | 1 1 1 1 1 1 1 1 1 2 2 2 2 2 1 1 1 1 | var AWS = require('../core');
var path = require('path');
/**
* Represents credentials loaded from shared credentials file
* (defaulting to ~/.aws/credentials).
*
* ## Using the shared credentials file
*
* This provider is checked by default in the Node.js environment. To use the
* credentials file provider, simply add your access and secret keys to the
* ~/.aws/credentials file in the following format:
*
* [default]
* aws_access_key_id = AKID...
* aws_secret_access_key = YOUR_SECRET_KEY
*
* ## Using custom profiles
*
* The SDK supports loading credentials for separate profiles. This can be done
* in two ways:
*
* 1. Set the `AWS_PROFILE` environment variable in your process prior to
* loading the SDK.
* 2. Directly load the AWS.SharedIniFileCredentials provider:
*
* ```javascript
* var creds = new AWS.SharedIniFileCredentials({profile: 'myprofile'});
* AWS.config.credentials = creds;
* ```
*
* @!macro nobrowser
*/
AWS.SharedIniFileCredentials = AWS.util.inherit(AWS.Credentials, {
/**
* Creates a new SharedIniFileCredentials object.
*
* @param options [map] a set of options
* @option options profile [String] (AWS_PROFILE env var or 'default')
* the name of the profile to load.
* @option options filename [String] ('~/.aws/credentials') the filename
* to use when loading credentials.
* @option options disableAssumeRole [Boolean] (false) True to disable
* support for profiles that assume an IAM role. If true, and an assume
* role profile is selected, an error is raised.
*/
constructor: function SharedIniFileCredentials(options) {
AWS.Credentials.call(this);
options = options || {};
this.filename = options.filename;
this.profile = options.profile || process.env.AWS_PROFILE || 'default';
this.disableAssumeRole = !!options.disableAssumeRole;
this.get(function() {});
},
/**
* Loads the credentials from the shared credentials file
*
* @callback callback function(err)
* Called after the shared INI file on disk is read and parsed. When this
* callback is called with no error, it means that the credentials
* information has been loaded into the object (as the `accessKeyId`,
* `secretAccessKey`, and `sessionToken` properties).
* @param err [Error] if an error occurred, this value will be filled
* @see get
*/
refresh: function refresh(callback) {
Iif (!callback) callback = function(err) { if (err) throw err; };
try {
if (!this.filename) this.loadDefaultFilename();
var creds = AWS.util.ini.parse(AWS.util.readFileSync(this.filename));
var profile = creds[this.profile];
if (typeof profile !== 'object') {
throw AWS.util.error(
new Error('Profile ' + this.profile + ' not found in ' + this.filename),
{ code: 'SharedIniFileCredentialsProviderFailure' }
);
}
if (profile['role_arn']) {
this.loadRoleProfile(creds, profile, callback);
return;
}
this.accessKeyId = profile['aws_access_key_id'];
this.secretAccessKey = profile['aws_secret_access_key'];
this.sessionToken = profile['aws_session_token'];
if (!this.accessKeyId || !this.secretAccessKey) {
throw AWS.util.error(
new Error('Credentials not set in ' + this.filename +
' using profile ' + this.profile),
{ code: 'SharedIniFileCredentialsProviderFailure' }
);
}
this.expired = false;
callback();
} catch (err) {
callback(err);
}
},
/**
* @api private
*/
loadRoleProfile: function loadRoleProfile(creds, roleProfile, callback) {
if (this.disableAssumeRole) {
throw AWS.util.error(
new Error('Role assumption profiles are disabled. ' +
'Failed to load profile ' + this.profile + ' from ' +
this.filename),
{ code: 'SharedIniFileCredentialsProviderFailure' }
);
}
var self = this;
var roleArn = roleProfile['role_arn'];
var roleSessionName = roleProfile['role_session_name'];
var externalId = roleProfile['external_id'];
var sourceProfileName = roleProfile['source_profile'];
if (!sourceProfileName) {
throw AWS.util.error(
new Error('source_profile is not set in ' + this.filename +
' using profile ' + this.profile),
{ code: 'SharedIniFileCredentialsProviderFailure' }
);
}
var sourceProfile = creds[sourceProfileName];
if (typeof sourceProfile !== 'object') {
throw AWS.util.error(
new Error('source_profile ' + sourceProfileName + ' set in ' +
this.filename + ' using profile ' + this.profile +
' does not exist'),
{ code: 'SharedIniFileCredentialsProviderFailure' }
);
}
var sourceCredentials = {
accessKeyId: sourceProfile['aws_access_key_id'],
secretAccessKey: sourceProfile['aws_secret_access_key'],
sessionToken: sourceProfile['aws_session_token']
};
if (!sourceCredentials.accessKeyId || !sourceCredentials.secretAccessKey) {
throw AWS.util.error(
new Error('Credentials not set in source_profile ' +
sourceProfileName + ' set in ' + this.filename +
' using profile ' + this.profile),
{ code: 'SharedIniFileCredentialsProviderFailure' }
);
}
var sts = new AWS.STS({
credentials: new AWS.Credentials(sourceCredentials)
});
var roleParams = {
RoleArn: roleArn,
RoleSessionName: roleSessionName || 'aws-sdk-js-' + Date.now()
};
if (externalId) {
roleParams.ExternalId = externalId;
}
sts.assumeRole(roleParams, function (err, data) {
if (err) {
callback(err);
return;
}
self.accessKeyId = data.Credentials.AccessKeyId;
self.secretAccessKey = data.Credentials.SecretAccessKey;
self.sessionToken = data.Credentials.SessionToken;
self.expireTime = data.Credentials.Expiration;
callback();
});
},
/**
* @api private
*/
loadDefaultFilename: function loadDefaultFilename() {
var env = process.env;
var home = env.HOME ||
env.USERPROFILE ||
(env.HOMEPATH ? ((env.HOMEDRIVE || 'C:/') + env.HOMEPATH) : null);
Iif (!home) {
throw AWS.util.error(
new Error('Cannot load credentials, HOME path not set'),
{ code: 'SharedIniFileCredentialsProviderFailure' }
);
}
this.filename = path.join(home, '.aws', 'credentials');
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | 1 1 | var AWS = require('../core');
/**
* Represents temporary credentials retrieved from {AWS.STS}. Without any
* extra parameters, credentials will be fetched from the
* {AWS.STS.getSessionToken} operation. If an IAM role is provided, the
* {AWS.STS.assumeRole} operation will be used to fetch credentials for the
* role instead.
*
* To setup temporary credentials, configure a set of master credentials
* using the standard credentials providers (environment, EC2 instance metadata,
* or from the filesystem), then set the global credentials to a new
* temporary credentials object:
*
* ```javascript
* // Note that environment credentials are loaded by default,
* // the following line is shown for clarity:
* AWS.config.credentials = new AWS.EnvironmentCredentials('AWS');
*
* // Now set temporary credentials seeded from the master credentials
* AWS.config.credentials = new AWS.TemporaryCredentials();
*
* // subsequent requests will now use temporary credentials from AWS STS.
* new AWS.S3().listBucket(function(err, data) { ... });
* ```
*
* @!attribute masterCredentials
* @return [AWS.Credentials] the master (non-temporary) credentials used to
* get and refresh temporary credentials from AWS STS.
* @note (see constructor)
*/
AWS.TemporaryCredentials = AWS.util.inherit(AWS.Credentials, {
/**
* Creates a new temporary credentials object.
*
* @note In order to create temporary credentials, you first need to have
* "master" credentials configured in {AWS.Config.credentials}. These
* master credentials are necessary to retrieve the temporary credentials,
* as well as refresh the credentials when they expire.
* @param params [map] a map of options that are passed to the
* {AWS.STS.assumeRole} or {AWS.STS.getSessionToken} operations.
* If a `RoleArn` parameter is passed in, credentials will be based on the
* IAM role.
* @example Creating a new credentials object for generic temporary credentials
* AWS.config.credentials = new AWS.TemporaryCredentials();
* @example Creating a new credentials object for an IAM role
* AWS.config.credentials = new AWS.TemporaryCredentials({
* RoleArn: 'arn:aws:iam::1234567890:role/TemporaryCredentials',
* });
* @see AWS.STS.assumeRole
* @see AWS.STS.getSessionToken
*/
constructor: function TemporaryCredentials(params) {
AWS.Credentials.call(this);
this.loadMasterCredentials();
this.expired = true;
this.params = params || {};
if (this.params.RoleArn) {
this.params.RoleSessionName =
this.params.RoleSessionName || 'temporary-credentials';
}
},
/**
* Refreshes credentials using {AWS.STS.assumeRole} or
* {AWS.STS.getSessionToken}, depending on whether an IAM role ARN was passed
* to the credentials {constructor}.
*
* @callback callback function(err)
* Called when the STS service responds (or fails). When
* this callback is called with no error, it means that the credentials
* information has been loaded into the object (as the `accessKeyId`,
* `secretAccessKey`, and `sessionToken` properties).
* @param err [Error] if an error occurred, this value will be filled
* @see get
*/
refresh: function refresh(callback) {
var self = this;
self.createClients();
if (!callback) callback = function(err) { if (err) throw err; };
self.service.config.credentials = self.masterCredentials;
var operation = self.params.RoleArn ?
self.service.assumeRole : self.service.getSessionToken;
operation.call(self.service, function (err, data) {
if (!err) {
self.service.credentialsFrom(data, self);
}
callback(err);
});
},
/**
* @api private
*/
loadMasterCredentials: function loadMasterCredentials() {
this.masterCredentials = AWS.config.credentials;
while (this.masterCredentials.masterCredentials) {
this.masterCredentials = this.masterCredentials.masterCredentials;
}
},
/**
* @api private
*/
createClients: function() {
this.service = this.service || new AWS.STS({params: this.params});
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | 1 1 | var AWS = require('../core');
/**
* Represents credentials retrieved from STS Web Identity Federation support.
*
* By default this provider gets credentials using the
* {AWS.STS.assumeRoleWithWebIdentity} service operation. This operation
* requires a `RoleArn` containing the ARN of the IAM trust policy for the
* application for which credentials will be given. In addition, the
* `WebIdentityToken` must be set to the token provided by the identity
* provider. See {constructor} for an example on creating a credentials
* object with proper `RoleArn` and `WebIdentityToken` values.
*
* ## Refreshing Credentials from Identity Service
*
* In addition to AWS credentials expiring after a given amount of time, the
* login token from the identity provider will also expire. Once this token
* expires, it will not be usable to refresh AWS credentials, and another
* token will be needed. The SDK does not manage refreshing of the token value,
* but this can be done through a "refresh token" supported by most identity
* providers. Consult the documentation for the identity provider for refreshing
* tokens. Once the refreshed token is acquired, you should make sure to update
* this new token in the credentials object's {params} property. The following
* code will update the WebIdentityToken, assuming you have retrieved an updated
* token from the identity provider:
*
* ```javascript
* AWS.config.credentials.params.WebIdentityToken = updatedToken;
* ```
*
* Future calls to `credentials.refresh()` will now use the new token.
*
* @!attribute params
* @return [map] the map of params passed to
* {AWS.STS.assumeRoleWithWebIdentity}. To update the token, set the
* `params.WebIdentityToken` property.
* @!attribute data
* @return [map] the raw data response from the call to
* {AWS.STS.assumeRoleWithWebIdentity}. Use this if you want to get
* access to other properties from the response.
*/
AWS.WebIdentityCredentials = AWS.util.inherit(AWS.Credentials, {
/**
* Creates a new credentials object.
* @param (see AWS.STS.assumeRoleWithWebIdentity)
* @example Creating a new credentials object
* AWS.config.credentials = new AWS.WebIdentityCredentials({
* RoleArn: 'arn:aws:iam::1234567890:role/WebIdentity',
* WebIdentityToken: 'ABCDEFGHIJKLMNOP', // token from identity service
* RoleSessionName: 'web' // optional name, defaults to web-identity
* });
* @see AWS.STS.assumeRoleWithWebIdentity
*/
constructor: function WebIdentityCredentials(params) {
AWS.Credentials.call(this);
this.expired = true;
this.params = params;
this.params.RoleSessionName = this.params.RoleSessionName || 'web-identity';
this.data = null;
},
/**
* Refreshes credentials using {AWS.STS.assumeRoleWithWebIdentity}
*
* @callback callback function(err)
* Called when the STS service responds (or fails). When
* this callback is called with no error, it means that the credentials
* information has been loaded into the object (as the `accessKeyId`,
* `secretAccessKey`, and `sessionToken` properties).
* @param err [Error] if an error occurred, this value will be filled
* @see get
*/
refresh: function refresh(callback) {
var self = this;
self.createClients();
if (!callback) callback = function(err) { if (err) throw err; };
self.service.assumeRoleWithWebIdentity(function (err, data) {
self.data = null;
if (!err) {
self.data = data;
self.service.credentialsFrom(data, self);
}
callback(err);
});
},
/**
* @api private
*/
createClients: function() {
this.service = this.service || new AWS.STS({params: this.params});
}
});
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| converter.js | 9.21% | (7 / 76) | 0% | (0 / 42) | 0% | (0 / 4) | 9.46% | (7 / 74) | |
| document_client.js | 4.35% | (5 / 115) | 0% | (0 / 38) | 0% | (0 / 18) | 4.46% | (5 / 112) | |
| set.js | 15.38% | (4 / 26) | 0% | (0 / 12) | 0% | (0 / 4) | 15.38% | (4 / 26) | |
| translator.js | 18.64% | (11 / 59) | 0% | (0 / 26) | 0% | (0 / 11) | 21.15% | (11 / 52) | |
| types.js | 17.39% | (4 / 23) | 0% | (0 / 26) | 0% | (0 / 2) | 19.05% | (4 / 21) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | 1 1 1 1 1 1 1 | var util = require('../core').util;
var typeOf = require('./types').typeOf;
var DynamoDBSet = require('./set');
function convertInput(data) {
if (typeOf(data) === 'Object') {
var map = {M: {}};
for (var key in data) {
map['M'][key] = convertInput(data[key]);
}
return map;
} else if (typeOf(data) === 'Array') {
var list = {L: []};
for (var i = 0; i < data.length; i++) {
list['L'].push(convertInput(data[i]));
}
return list;
} else if (typeOf(data) === 'Set') {
return formatSet(data);
} else if (typeOf(data) === 'String') {
return { 'S': data };
} else if (typeOf(data) === 'Number') {
return { 'N': data.toString() };
} else if (typeOf(data) === 'Binary') {
return { 'B': data };
} else if (typeOf(data) === 'Boolean') {
return {'BOOL': data};
} else if (typeOf(data) === 'null') {
return {'NULL': true};
}
}
function formatSet(data) {
var map = {};
switch (data.type) {
case 'String': map['SS'] = data.values; break;
case 'Binary': map['BS'] = data.values; break;
case 'Number': map['NS'] = data.values.map(function (value) {
return value.toString();
});
}
return map;
}
function convertOutput(data) {
var list, map, i;
for (var type in data) {
var values = data[type];
if (type === 'M') {
map = {};
for (var key in values) {
map[key] = convertOutput(values[key]);
}
return map;
} else if (type === 'L') {
list = [];
for (i = 0; i < values.length; i++) {
list.push(convertOutput(values[i]));
}
return list;
} else if (type === 'SS') {
list = [];
for (i = 0; i < values.length; i++) {
list.push(values[i] + '');
}
return new DynamoDBSet(list);
} else if (type === 'NS') {
list = [];
for (i = 0; i < values.length; i++) {
list.push(Number(values[i]));
}
return new DynamoDBSet(list);
} else if (type === 'BS') {
list = [];
for (i = 0; i < values.length; i++) {
list.push(new util.Buffer(values[i]));
}
return new DynamoDBSet(list);
} else if (type === 'S') {
return values + '';
} else if (type === 'N') {
return Number(values);
} else if (type === 'B') {
return new util.Buffer(values);
} else if (type === 'BOOL') {
return (values === 'true' || values === 'TRUE' || values === true);
} else if (type === 'NULL') {
return null;
}
}
}
module.exports = {
input: convertInput,
output: convertOutput
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 | 1 1 1 1 1 | var AWS = require('../core');
var Translator = require('./translator');
var DynamoDBSet = require('./set');
/**
* The document client simplifies working with items in Amazon DynamoDB
* by abstracting away the notion of attribute values. This abstraction
* annotates native JavaScript types supplied as input parameters, as well
* as converts annotated response data to native JavaScript types.
*
* ## Marshalling Input and Unmarshalling Response Data
*
* The document client affords developers the use of native JavaScript types
* instead of `AttributeValue`s to simplify the JavaScript development
* experience with Amazon DynamoDB. JavaScript objects passed in as parameters
* are marshalled into `AttributeValue` shapes required by Amazon DynamoDB.
* Responses from DynamoDB are unmarshalled into plain JavaScript objects
* by the `DocumentClient`. The `DocumentClient`, does not accept
* `AttributeValue`s in favor of native JavaScript types.
*
* | JavaScript Type | DynamoDB AttributeValue |
* |:----------------------------------------------------------------------:|-------------------------|
* | String | S |
* | Number | N |
* | Boolean | BOOL |
* | null | NULL |
* | Array | L |
* | Object | M |
* | Buffer, File, Blob, ArrayBuffer, DataView, and JavaScript typed arrays | B |
*
* ## Support for Sets
*
* The `DocumentClient` offers a convenient way to create sets from
* JavaScript Arrays. The type of set is inferred from the first element
* in the array. DynamoDB supports string, number, and binary sets. To
* learn more about supported types see the
* [Amazon DynamoDB Data Model Documentation](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html)
* For more information see {AWS.DynamoDB.DocumentClient.createSet}
*
*/
AWS.DynamoDB.DocumentClient = AWS.util.inherit({
/**
* @api private
*/
operations: {
batchGetItem: 'batchGet',
batchWriteItem: 'batchWrite',
putItem: 'put',
getItem: 'get',
deleteItem: 'delete',
updateItem: 'update',
scan: 'scan',
query: 'query'
},
/**
* Creates a DynamoDB document client with a set of configuration options.
*
* @option options params [map] An optional map of parameters to bind to every
* request sent by this service object.
* @option options service [AWS.DynamoDB] An optional pre-configured instance
* of the AWS.DynamoDB service object to use for requests. The object may
* bound parameters used by the document client.
* @see AWS.DynamoDB.constructor
*
*/
constructor: function DocumentClient(options) {
var self = this;
self.options = options || {};
self.configure(self.options);
},
/**
* @api private
*/
configure: function configure(options) {
var self = this;
self.service = options.service;
self.bindServiceObject(options);
self.attrValue =
self.service.api.operations.putItem.input.members.Item.value.shape;
},
/**
* @api private
*/
bindServiceObject: function bindServiceObject(options) {
var self = this;
options = options || {};
if (!self.service) {
self.service = new AWS.DynamoDB(options);
} else {
var config = AWS.util.copy(self.service.config);
self.service = new self.service.constructor.__super__(config);
self.service.config.params =
AWS.util.merge(self.service.config.params || {}, options.params);
}
},
/**
* Returns the attributes of one or more items from one or more tables
* by delegating to `AWS.DynamoDB.batchGetItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.batchGetItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.batchGetItem
* @example Get items from multiple tables
* var params = {
* RequestItems: {
* 'Table-1': {
* Keys: [
* {
* HashKey: 'haskey',
* NumberRangeKey: 1
* }
* ]
* },
* 'Table-2': {
* Keys: [
* { foo: 'bar' },
* ]
* }
* }
* };
*
* var docClient = new AWS.DynamoDB.DocumentClient();
*
* docClient.batchGet(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
batchGet: function(params, callback) {
var self = this;
var request = self.service.batchGetItem(params);
self.setupRequest(request);
self.setupResponse(request);
if (typeof callback === 'function') {
request.send(callback);
}
return request;
},
/**
* Puts or deletes multiple items in one or more tables by delegating
* to `AWS.DynamoDB.batchWriteItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.batchWriteItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.batchWriteItem
* @example Write to and delete from a table
* var params = {
* RequestItems: {
* 'Table-1': [
* {
* DeleteRequest: {
* Key: { HashKey: 'someKey' }
* }
* },
* {
* PutRequest: {
* Item: {
* HashKey: 'anotherKey',
* NumAttribute: 1,
* BoolAttribute: true,
* ListAttribute: [1, 'two', false],
* MapAttribute: { foo: 'bar' }
* }
* }
* }
* ]
* }
* };
*
* var docClient = new AWS.DynamoDB.DocumentClient();
*
* docClient.batchWrite(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
batchWrite: function(params, callback) {
var self = this;
var request = self.service.batchWriteItem(params);
self.setupRequest(request);
self.setupResponse(request);
if (typeof callback === 'function') {
request.send(callback);
}
return request;
},
/**
* Deletes a single item in a table by primary key by delegating to
* `AWS.DynamoDB.deleteItem()`
*
* Supply the same parameters as {AWS.DynamoDB.deleteItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.deleteItem
* @example Delete an item from a table
* var params = {
* TableName : 'Table',
* Key: {
* HashKey: 'hashkey',
* NumberRangeKey: 1
* }
* };
*
* var docClient = new AWS.DynamoDB.DocumentClient();
*
* docClient.delete(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
delete: function(params, callback) {
var self = this;
var request = self.service.deleteItem(params);
self.setupRequest(request);
self.setupResponse(request);
if (typeof callback === 'function') {
request.send(callback);
}
return request;
},
/**
* Returns a set of attributes for the item with the given primary key
* by delegating to `AWS.DynamoDB.getItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.getItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.getItem
* @example Get an item from a table
* var params = {
* TableName : 'Table',
* Key: {
* HashKey: 'hashkey'
* }
* };
*
* var docClient = new AWS.DynamoDB.DocumentClient();
*
* docClient.get(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
get: function(params, callback) {
var self = this;
var request = self.service.getItem(params);
self.setupRequest(request);
self.setupResponse(request);
if (typeof callback === 'function') {
request.send(callback);
}
return request;
},
/**
* Creates a new item, or replaces an old item with a new item by
* delegating to `AWS.DynamoDB.putItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.putItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.putItem
* @example Create a new item in a table
* var params = {
* TableName : 'Table',
* Item: {
* HashKey: 'haskey',
* NumAttribute: 1,
* BoolAttribute: true,
* ListAttribute: [1, 'two', false],
* MapAttribute: { foo: 'bar'},
* NullAttribute: null
* }
* };
*
* var docClient = new AWS.DynamoDB.DocumentClient();
*
* docClient.put(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
put: function put(params, callback) {
var self = this;
var request = self.service.putItem(params);
self.setupRequest(request);
self.setupResponse(request);
if (typeof callback === 'function') {
request.send(callback);
}
return request;
},
/**
* Edits an existing item's attributes, or adds a new item to the table if
* it does not already exist by delegating to `AWS.DynamoDB.updateItem()`.
*
* Supply the same parameters as {AWS.DynamoDB.updateItem} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.updateItem
* @example Update an item with expressions
* var params = {
* TableName: 'Table',
* Key: { HashKey : 'hashkey' },
* UpdateExpression: 'set #a = :x + :y',
* ConditionExpression: '#a < :MAX',
* ExpressionAttributeNames: {'#a' : 'Sum'},
* ExpressionAttributeValues: {
* ':x' : 20,
* ':y' : 45,
* ':MAX' : 100,
* }
* };
*
* var docClient = new AWS.DynamoDB.DocumentClient();
*
* docClient.update(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
update: function(params, callback) {
var self = this;
var request = self.service.updateItem(params);
self.setupRequest(request);
self.setupResponse(request);
if (typeof callback === 'function') {
request.send(callback);
}
return request;
},
/**
* Returns one or more items and item attributes by accessing every item
* in a table or a secondary index.
*
* Supply the same parameters as {AWS.DynamoDB.scan} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.scan
* @example Scan the table with a filter expression
* var params = {
* TableName : 'Table',
* FilterExpression : 'Year = :this_year',
* ExpressionAttributeValues : {':this_year' : 2015}
* };
*
* var docClient = new AWS.DynamoDB.DocumentClient();
*
* docClient.scan(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
scan: function(params, callback) {
var self = this;
var request = self.service.scan(params);
self.setupRequest(request);
self.setupResponse(request);
if (typeof callback === 'function') {
request.send(callback);
}
return request;
},
/**
* Directly access items from a table by primary key or a secondary index.
*
* Supply the same parameters as {AWS.DynamoDB.query} with
* `AttributeValue`s substituted by native JavaScript types.
*
* @see AWS.DynamoDB.query
* @example Query an index
* var params = {
* TableName: 'Table',
* IndexName: 'Index',
* KeyConditionExpression: 'HashKey = :hkey and RangeKey > :rkey',
* ExpressionAttributeValues: {
* ':hkey': 'key',
* ':rkey': 2015
* }
* };
*
* var docClient = new AWS.DynamoDB.DocumentClient();
*
* docClient.query(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
query: function(params, callback) {
var self = this;
var request = self.service.query(params);
self.setupRequest(request);
self.setupResponse(request);
if (typeof callback === 'function') {
request.send(callback);
}
return request;
},
/**
* Creates a set of elements inferring the type of set from
* the type of the first element. Amazon DynamoDB currently supports
* the number sets, string sets, and binary sets. For more information
* about DynamoDB data types see the documentation on the
* [Amazon DynamoDB Data Model](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataModel.html#DataModel.DataTypes).
*
* @param list [Array] Collection to represent your DynamoDB Set
* @param options [map]
* * **validate** [Boolean] set to true if you want to validate the type
* of each element in the set. Defaults to `false`.
* @example Creating a number set
* var docClient = new AWS.DynamoDB.DocumentClient();
*
* var params = {
* Item: {
* hashkey: 'hashkey'
* numbers: docClient.createSet([1, 2, 3]);
* }
* };
*
* docClient.put(params, function(err, data) {
* if (err) console.log(err);
* else console.log(data);
* });
*
*/
createSet: function(list, options) {
options = options || {};
return new DynamoDBSet(list, options);
},
/**
* @api private
*/
getTranslator: function() {
return new Translator({attrValue: this.attrValue});
},
/**
* @api private
*/
setupRequest: function setupRequest(request) {
var self = this;
var translator = self.getTranslator();
var operation = request.operation;
var inputShape = request.service.api.operations[operation].input;
request._events.validate.unshift(function(req) {
req.rawParams = AWS.util.copy(req.params);
req.params = translator.translateInput(req.rawParams, inputShape);
});
},
/**
* @api private
*/
setupResponse: function setupResponse(request) {
var self = this;
var translator = self.getTranslator();
var outputShape = self.service.api.operations[request.operation].output;
request.on('extractData', function(response) {
response.data = translator.translateOutput(response.data, outputShape);
});
var response = request.response;
response.nextPage = function(cb) {
var resp = this;
var req = resp.request;
var config;
var service = req.service;
var operation = req.operation;
try {
config = service.paginationConfig(operation, true);
} catch (e) { resp.error = e; }
if (!resp.hasNextPage()) {
if (cb) cb(resp.error, null);
else if (resp.error) throw resp.error;
return null;
}
var params = AWS.util.copy(req.rawParams);
if (!resp.nextPageTokens) {
return cb ? cb(null, null) : null;
} else {
var inputTokens = config.inputToken;
if (typeof inputTokens === 'string') inputTokens = [inputTokens];
for (var i = 0; i < inputTokens.length; i++) {
params[inputTokens[i]] = resp.nextPageTokens[i];
}
return self[operation](params, cb);
}
};
}
});
module.exports = AWS.DynamoDB.DocumentClient;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 1 1 1 1 | var util = require('../core').util;
var typeOf = require('./types').typeOf;
var DynamoDBSet = util.inherit({
constructor: function Set(list, options) {
options = options || {};
this.initialize(list, options.validate);
},
initialize: function(list, validate) {
var self = this;
self.values = [].concat(list);
self.detectType();
if (validate) {
self.validate();
}
},
detectType: function() {
var self = this;
var value = self.values[0];
if (typeOf(value) === 'String') {
self.type = 'String';
} else if (typeOf(value) === 'Number') {
self.type = 'Number';
} else if (typeOf(value) === 'Binary') {
self.type = 'Binary';
} else {
throw util.error(new Error(), {
code: 'InvalidSetType',
message: 'Sets can contain string, number, or binary values'
});
}
},
validate: function() {
var self = this;
var length = self.values.length;
var values = self.values;
for (var i = 0; i < length; i++) {
if (typeOf(values[i]) !== self.type) {
throw util.error(new Error(), {
code: 'InvalidType',
message: self.type + ' Set contains ' + typeOf(values[i]) + ' value'
});
}
}
}
});
module.exports = DynamoDBSet;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | 1 1 1 1 1 1 1 1 1 1 1 | var util = require('../core').util;
var convert = require('./converter');
var Translator = function(options) {
options = options || {};
this.attrValue = options.attrValue;
};
Translator.prototype.translateInput = function(value, shape) {
this.mode = 'input';
return this.translate(value, shape);
};
Translator.prototype.translateOutput = function(value, shape) {
this.mode = 'output';
return this.translate(value, shape);
};
Translator.prototype.translate = function(value, shape) {
var self = this;
if (!shape || value === undefined) return undefined;
if (shape.shape === self.attrValue) {
return convert[self.mode](value);
}
switch (shape.type) {
case 'structure': return self.translateStructure(value, shape);
case 'map': return self.translateMap(value, shape);
case 'list': return self.translateList(value, shape);
default: return self.translateScalar(value, shape);
}
};
Translator.prototype.translateStructure = function(structure, shape) {
var self = this;
if (structure == null) return undefined;
var struct = {};
util.each(structure, function(name, value) {
var memberShape = shape.members[name];
if (memberShape) {
var result = self.translate(value, memberShape);
if (result !== undefined) struct[name] = result;
}
});
return struct;
};
Translator.prototype.translateList = function(list, shape) {
var self = this;
if (list == null) return undefined;
var out = [];
util.arrayEach(list, function(value) {
var result = self.translate(value, shape.member);
if (result === undefined) out.push(null);
else out.push(result);
});
return out;
};
Translator.prototype.translateMap = function(map, shape) {
var self = this;
if (map == null) return undefined;
var out = {};
util.each(map, function(key, value) {
var result = self.translate(value, shape.value);
if (result === undefined) out[key] = null;
else out[key] = result;
});
return out;
};
Translator.prototype.translateScalar = function(value, shape) {
return shape.toType(value);
};
module.exports = Translator;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 1 1 1 1 | var util = require('../core').util;
function typeOf(data) {
if (data === null && typeof data === 'object') {
return 'null';
} else if (data !== undefined && isBinary(data)) {
return 'Binary';
} else if (data !== undefined && data.constructor) {
return util.typeName(data.constructor);
} else {
return 'undefined';
}
}
function isBinary(data) {
var types = [
'Buffer', 'File', 'Blob', 'ArrayBuffer', 'DataView',
'Int8Array', 'Uint8Array', 'Uint8ClampedArray',
'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array',
'Float32Array', 'Float64Array'
];
if (util.isNode()) {
var Stream = util.nodeRequire('stream').Stream;
if (util.Buffer.isBuffer(data) || data instanceof Stream)
return true;
} else {
for (var i = 0; i < types.length; i++) {
if (data !== undefined && data.constructor) {
if (util.isType(data, types[i])) return true;
if (util.typeName(data.constructor) === types[i]) return true;
}
}
}
return false;
}
module.exports = {
typeOf: typeOf,
isBinary: isBinary
};
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| node.js | 9.88% | (8 / 81) | 2.38% | (1 / 42) | 0% | (0 / 11) | 10.81% | (8 / 74) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | 1 1 1 1 1 1 1 1 | var AWS = require('../core');
var Stream = AWS.util.nodeRequire('stream').Stream;
var TransformStream = AWS.util.nodeRequire('stream').Transform;
var ReadableStream = AWS.util.nodeRequire('stream').Readable;
require('../http');
/**
* @api private
*/
AWS.NodeHttpClient = AWS.util.inherit({
handleRequest: function handleRequest(httpRequest, httpOptions, callback, errCallback) {
var self = this;
var cbAlreadyCalled = false;
var endpoint = httpRequest.endpoint;
var pathPrefix = '';
if (!httpOptions) httpOptions = {};
if (httpOptions.proxy) {
pathPrefix = endpoint.protocol + '//' + endpoint.hostname;
if (endpoint.port !== 80 && endpoint.port !== 443) {
pathPrefix += ':' + endpoint.port;
}
endpoint = new AWS.Endpoint(httpOptions.proxy);
}
var useSSL = endpoint.protocol === 'https:';
var http = useSSL ? require('https') : require('http');
var options = {
host: endpoint.hostname,
port: endpoint.port,
method: httpRequest.method,
headers: httpRequest.headers,
path: pathPrefix + httpRequest.path
};
if (useSSL && !httpOptions.agent) {
options.agent = this.sslAgent();
}
AWS.util.update(options, httpOptions);
delete options.proxy; // proxy isn't an HTTP option
delete options.timeout; // timeout isn't an HTTP option
var stream = http.request(options, function (httpResp) {
if (cbAlreadyCalled) return; cbAlreadyCalled = true;
callback(httpResp);
httpResp.emit('headers', httpResp.statusCode, httpResp.headers);
});
httpRequest.stream = stream; // attach stream to httpRequest
// timeout support
stream.setTimeout(httpOptions.timeout || 0, function() {
if (cbAlreadyCalled) return; cbAlreadyCalled = true;
var msg = 'Connection timed out after ' + httpOptions.timeout + 'ms';
errCallback(AWS.util.error(new Error(msg), {code: 'TimeoutError'}));
stream.abort();
});
stream.on('error', function() {
if (cbAlreadyCalled) return; cbAlreadyCalled = true;
errCallback.apply(this, arguments);
});
var expect = httpRequest.headers.Expect || httpRequest.headers.expect;
if (expect === '100-continue') {
stream.on('continue', function() {
self.writeBody(stream, httpRequest);
});
} else {
this.writeBody(stream, httpRequest);
}
return stream;
},
writeBody: function writeBody(stream, httpRequest) {
var body = httpRequest.body;
var totalBytes = parseInt(httpRequest.headers['Content-Length'], 10);
if (body instanceof Stream) {
// For progress support of streaming content -
// pipe the data through a transform stream to emit 'sendProgress' events
var progressStream = this.progressStream(stream, totalBytes);
if (progressStream) {
body.pipe(progressStream).pipe(stream);
} else {
body.pipe(stream);
}
} else if (body) {
// The provided body is a buffer/string and is already fully available in memory -
// For performance it's best to send it as a whole by calling stream.end(body),
// Callers expect a 'sendProgress' event which is best emitted once
// the http request stream has been fully written and all data flushed.
// The use of totalBytes is important over body.length for strings where
// length is char length and not byte length.
stream.once('finish', function() {
stream.emit('sendProgress', {
loaded: totalBytes,
total: totalBytes
});
});
stream.end(body);
} else {
// no request body
stream.end();
}
},
sslAgent: function sslAgent() {
var https = require('https');
if (!AWS.NodeHttpClient.sslAgent) {
AWS.NodeHttpClient.sslAgent = new https.Agent({rejectUnauthorized: true});
AWS.NodeHttpClient.sslAgent.setMaxListeners(0);
// delegate maxSockets to globalAgent, set a default limit of 50 if current value is Infinity.
// Users can bypass this default by supplying their own Agent as part of SDK configuration.
Object.defineProperty(AWS.NodeHttpClient.sslAgent, 'maxSockets', {
enumerable: true,
get: function() {
return https.globalAgent.maxSockets !== Infinity ? https.globalAgent.maxSockets : 50;
}
});
}
return AWS.NodeHttpClient.sslAgent;
},
progressStream: function progressStream(stream, totalBytes) {
if (typeof TransformStream === 'undefined') {
// for node 0.8 there is no streaming progress
return;
}
var loadedBytes = 0;
var reporter = new TransformStream();
reporter._transform = function(chunk, encoding, callback) {
if (chunk) {
loadedBytes += chunk.length;
stream.emit('sendProgress', {
loaded: loadedBytes,
total: totalBytes
});
}
callback(null, chunk);
};
return reporter;
},
emitter: null
});
/**
* @!ignore
*/
/**
* @api private
*/
AWS.HttpClient.prototype = AWS.NodeHttpClient.prototype;
/**
* @api private
*/
AWS.HttpClient.streamsApiVersion = ReadableStream ? 2 : 1;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| builder.js | 21.95% | (9 / 41) | 0% | (0 / 21) | 0% | (0 / 10) | 25% | (9 / 36) | |
| parser.js | 18.75% | (9 / 48) | 0% | (0 / 24) | 0% | (0 / 10) | 21.95% | (9 / 41) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | 1 1 1 1 1 1 1 1 1 | var util = require('../util');
function JsonBuilder() { }
JsonBuilder.prototype.build = function(value, shape) {
return JSON.stringify(translate(value, shape));
};
function translate(value, shape) {
if (!shape || value === undefined || value === null) return undefined;
switch (shape.type) {
case 'structure': return translateStructure(value, shape);
case 'map': return translateMap(value, shape);
case 'list': return translateList(value, shape);
default: return translateScalar(value, shape);
}
}
function translateStructure(structure, shape) {
var struct = {};
util.each(structure, function(name, value) {
var memberShape = shape.members[name];
if (memberShape) {
if (memberShape.location !== 'body') return;
var locationName = memberShape.isLocationName ? memberShape.name : name;
var result = translate(value, memberShape);
if (result !== undefined) struct[locationName] = result;
}
});
return struct;
}
function translateList(list, shape) {
var out = [];
util.arrayEach(list, function(value) {
var result = translate(value, shape.member);
if (result !== undefined) out.push(result);
});
return out;
}
function translateMap(map, shape) {
var out = {};
util.each(map, function(key, value) {
var result = translate(value, shape.value);
if (result !== undefined) out[key] = result;
});
return out;
}
function translateScalar(value, shape) {
return shape.toWireFormat(value);
}
module.exports = JsonBuilder;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | 1 1 1 1 1 1 1 1 1 | var util = require('../util');
function JsonParser() { }
JsonParser.prototype.parse = function(value, shape) {
return translate(JSON.parse(value), shape);
};
function translate(value, shape) {
if (!shape || value === undefined) return undefined;
switch (shape.type) {
case 'structure': return translateStructure(value, shape);
case 'map': return translateMap(value, shape);
case 'list': return translateList(value, shape);
default: return translateScalar(value, shape);
}
}
function translateStructure(structure, shape) {
if (structure == null) return undefined;
var struct = {};
var shapeMembers = shape.members;
util.each(shapeMembers, function(name, memberShape) {
var locationName = memberShape.isLocationName ? memberShape.name : name;
if (Object.prototype.hasOwnProperty.call(structure, locationName)) {
var value = structure[locationName];
var result = translate(value, memberShape);
if (result !== undefined) struct[name] = result;
}
});
return struct;
}
function translateList(list, shape) {
if (list == null) return undefined;
var out = [];
util.arrayEach(list, function(value) {
var result = translate(value, shape.member);
if (result === undefined) out.push(null);
else out.push(result);
});
return out;
}
function translateMap(map, shape) {
if (map == null) return undefined;
var out = {};
util.each(map, function(key, value) {
var result = translate(value, shape.value);
if (result === undefined) out[key] = null;
else out[key] = result;
});
return out;
}
function translateScalar(value, shape) {
return shape.toType(value);
}
module.exports = JsonParser;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| api.js | 21.74% | (10 / 46) | 0% | (0 / 14) | 0% | (0 / 6) | 22.73% | (10 / 44) | |
| collection.js | 36.36% | (4 / 11) | 0% | (0 / 4) | 0% | (0 / 3) | 36.36% | (4 / 11) | |
| operation.js | 18.18% | (6 / 33) | 0% | (0 / 20) | 0% | (0 / 5) | 18.75% | (6 / 32) | |
| paginator.js | 37.5% | (3 / 8) | 100% | (0 / 0) | 0% | (0 / 1) | 37.5% | (3 / 8) | |
| resource_waiter.js | 26.67% | (4 / 15) | 0% | (0 / 6) | 0% | (0 / 2) | 26.67% | (4 / 15) | |
| shape.js | 11.17% | (22 / 197) | 0% | (0 / 139) | 0% | (0 / 37) | 12.22% | (22 / 180) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | 1 1 1 1 1 1 1 1 1 1 | var Collection = require('./collection');
var Operation = require('./operation');
var Shape = require('./shape');
var Paginator = require('./paginator');
var ResourceWaiter = require('./resource_waiter');
var util = require('../util');
var property = util.property;
var memoizedProperty = util.memoizedProperty;
function Api(api, options) {
api = api || {};
options = options || {};
options.api = this;
api.metadata = api.metadata || {};
property(this, 'isApi', true, false);
property(this, 'apiVersion', api.metadata.apiVersion);
property(this, 'endpointPrefix', api.metadata.endpointPrefix);
property(this, 'signingName', api.metadata.signingName);
property(this, 'globalEndpoint', api.metadata.globalEndpoint);
property(this, 'signatureVersion', api.metadata.signatureVersion);
property(this, 'jsonVersion', api.metadata.jsonVersion);
property(this, 'targetPrefix', api.metadata.targetPrefix);
property(this, 'protocol', api.metadata.protocol);
property(this, 'timestampFormat', api.metadata.timestampFormat);
property(this, 'xmlNamespaceUri', api.metadata.xmlNamespace);
property(this, 'abbreviation', api.metadata.serviceAbbreviation);
property(this, 'fullName', api.metadata.serviceFullName);
memoizedProperty(this, 'className', function() {
var name = api.metadata.serviceAbbreviation || api.metadata.serviceFullName;
if (!name) return null;
name = name.replace(/^Amazon|AWS\s*|\(.*|\s+|\W+/g, '');
if (name === 'ElasticLoadBalancing') name = 'ELB';
return name;
});
property(this, 'operations', new Collection(api.operations, options, function(name, operation) {
return new Operation(name, operation, options);
}, util.string.lowerFirst));
property(this, 'shapes', new Collection(api.shapes, options, function(name, shape) {
return Shape.create(shape, options);
}));
property(this, 'paginators', new Collection(api.paginators, options, function(name, paginator) {
return new Paginator(name, paginator, options);
}));
property(this, 'waiters', new Collection(api.waiters, options, function(name, waiter) {
return new ResourceWaiter(name, waiter, options);
}, util.string.lowerFirst));
if (options.documentation) {
property(this, 'documentation', api.documentation);
property(this, 'documentationUrl', api.documentationUrl);
}
}
module.exports = Api;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 1 1 1 1 | var memoizedProperty = require('../util').memoizedProperty;
function memoize(name, value, fn, nameTr) {
memoizedProperty(this, nameTr(name), function() {
return fn(name, value);
});
}
function Collection(iterable, options, fn, nameTr) {
nameTr = nameTr || String;
var self = this;
for (var id in iterable) {
if (Object.prototype.hasOwnProperty.call(iterable, id)) {
memoize.call(self, id, iterable[id], fn, nameTr);
}
}
}
module.exports = Collection;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 1 1 1 1 1 1 | var Shape = require('./shape');
var util = require('../util');
var property = util.property;
var memoizedProperty = util.memoizedProperty;
function Operation(name, operation, options) {
options = options || {};
property(this, 'name', operation.name || name);
property(this, 'api', options.api, false);
operation.http = operation.http || {};
property(this, 'httpMethod', operation.http.method || 'POST');
property(this, 'httpPath', operation.http.requestUri || '/');
property(this, 'authtype', operation.authtype || '');
memoizedProperty(this, 'input', function() {
if (!operation.input) {
return new Shape.create({type: 'structure'}, options);
}
return Shape.create(operation.input, options);
});
memoizedProperty(this, 'output', function() {
if (!operation.output) {
return new Shape.create({type: 'structure'}, options);
}
return Shape.create(operation.output, options);
});
memoizedProperty(this, 'errors', function() {
var list = [];
if (!operation.errors) return null;
for (var i = 0; i < operation.errors.length; i++) {
list.push(Shape.create(operation.errors[i], options));
}
return list;
});
memoizedProperty(this, 'paginator', function() {
return options.api.paginators[name];
});
if (options.documentation) {
property(this, 'documentation', operation.documentation);
property(this, 'documentationUrl', operation.documentationUrl);
}
}
module.exports = Operation;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | 1 1 1 | var property = require('../util').property;
function Paginator(name, paginator) {
property(this, 'inputToken', paginator.input_token);
property(this, 'limitKey', paginator.limit_key);
property(this, 'moreResults', paginator.more_results);
property(this, 'outputToken', paginator.output_token);
property(this, 'resultKey', paginator.result_key);
}
module.exports = Paginator;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 1 1 1 1 | var util = require('../util');
var property = util.property;
function ResourceWaiter(name, waiter, options) {
options = options || {};
property(this, 'name', name);
property(this, 'api', options.api, false);
if (waiter.operation) {
property(this, 'operation', util.string.lowerFirst(waiter.operation));
}
var self = this;
var keys = [
'type',
'description',
'delay',
'maxAttempts',
'acceptors'
];
keys.forEach(function(key) {
var value = waiter[key];
if (value) {
property(self, key, value);
}
});
}
module.exports = ResourceWaiter;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | var Collection = require('./collection');
var util = require('../util');
function property(obj, name, value) {
if (value !== null && value !== undefined) {
util.property.apply(this, arguments);
}
}
function memoizedProperty(obj, name) {
if (!obj.constructor.prototype[name]) {
util.memoizedProperty.apply(this, arguments);
}
}
function Shape(shape, options, memberName) {
options = options || {};
property(this, 'shape', shape.shape);
property(this, 'api', options.api, false);
property(this, 'type', shape.type);
property(this, 'enum', shape.enum);
property(this, 'min', shape.min);
property(this, 'max', shape.max);
property(this, 'pattern', shape.pattern);
property(this, 'location', shape.location || this.location || 'body');
property(this, 'name', this.name || shape.xmlName || shape.queryName ||
shape.locationName || memberName);
property(this, 'isStreaming', shape.streaming || this.isStreaming || false);
property(this, 'isComposite', shape.isComposite || false);
property(this, 'isShape', true, false);
property(this, 'isQueryName', shape.queryName ? true : false, false);
property(this, 'isLocationName', shape.locationName ? true : false, false);
if (options.documentation) {
property(this, 'documentation', shape.documentation);
property(this, 'documentationUrl', shape.documentationUrl);
}
if (shape.xmlAttribute) {
property(this, 'isXmlAttribute', shape.xmlAttribute || false);
}
// type conversion and parsing
property(this, 'defaultValue', null);
this.toWireFormat = function(value) {
if (value === null || value === undefined) return '';
return value;
};
this.toType = function(value) { return value; };
}
/**
* @api private
*/
Shape.normalizedTypes = {
character: 'string',
double: 'float',
long: 'integer',
short: 'integer',
biginteger: 'integer',
bigdecimal: 'float',
blob: 'binary'
};
/**
* @api private
*/
Shape.types = {
'structure': StructureShape,
'list': ListShape,
'map': MapShape,
'boolean': BooleanShape,
'timestamp': TimestampShape,
'float': FloatShape,
'integer': IntegerShape,
'string': StringShape,
'base64': Base64Shape,
'binary': BinaryShape
};
Shape.resolve = function resolve(shape, options) {
if (shape.shape) {
var refShape = options.api.shapes[shape.shape];
if (!refShape) {
throw new Error('Cannot find shape reference: ' + shape.shape);
}
return refShape;
} else {
return null;
}
};
Shape.create = function create(shape, options, memberName) {
if (shape.isShape) return shape;
var refShape = Shape.resolve(shape, options);
if (refShape) {
var filteredKeys = Object.keys(shape);
if (!options.documentation) {
filteredKeys = filteredKeys.filter(function(name) {
return !name.match(/documentation/);
});
}
if (filteredKeys === ['shape']) { // no inline customizations
return refShape;
}
// create an inline shape with extra members
var InlineShape = function() {
refShape.constructor.call(this, shape, options, memberName);
};
InlineShape.prototype = refShape;
return new InlineShape();
} else {
// set type if not set
if (!shape.type) {
if (shape.members) shape.type = 'structure';
else if (shape.member) shape.type = 'list';
else if (shape.key) shape.type = 'map';
else shape.type = 'string';
}
// normalize types
var origType = shape.type;
if (Shape.normalizedTypes[shape.type]) {
shape.type = Shape.normalizedTypes[shape.type];
}
if (Shape.types[shape.type]) {
return new Shape.types[shape.type](shape, options, memberName);
} else {
throw new Error('Unrecognized shape type: ' + origType);
}
}
};
function CompositeShape(shape) {
Shape.apply(this, arguments);
property(this, 'isComposite', true);
if (shape.flattened) {
property(this, 'flattened', shape.flattened || false);
}
}
function StructureShape(shape, options) {
var requiredMap = null, firstInit = !this.isShape;
CompositeShape.apply(this, arguments);
if (firstInit) {
property(this, 'defaultValue', function() { return {}; });
property(this, 'members', {});
property(this, 'memberNames', []);
property(this, 'required', []);
property(this, 'isRequired', function() { return false; });
}
if (shape.members) {
property(this, 'members', new Collection(shape.members, options, function(name, member) {
return Shape.create(member, options, name);
}));
memoizedProperty(this, 'memberNames', function() {
return shape.xmlOrder || Object.keys(shape.members);
});
}
if (shape.required) {
property(this, 'required', shape.required);
property(this, 'isRequired', function(name) {
if (!requiredMap) {
requiredMap = {};
for (var i = 0; i < shape.required.length; i++) {
requiredMap[shape.required[i]] = true;
}
}
return requiredMap[name];
}, false, true);
}
property(this, 'resultWrapper', shape.resultWrapper || null);
if (shape.payload) {
property(this, 'payload', shape.payload);
}
if (typeof shape.xmlNamespace === 'string') {
property(this, 'xmlNamespaceUri', shape.xmlNamespace);
} else if (typeof shape.xmlNamespace === 'object') {
property(this, 'xmlNamespacePrefix', shape.xmlNamespace.prefix);
property(this, 'xmlNamespaceUri', shape.xmlNamespace.uri);
}
}
function ListShape(shape, options) {
var self = this, firstInit = !this.isShape;
CompositeShape.apply(this, arguments);
if (firstInit) {
property(this, 'defaultValue', function() { return []; });
}
if (shape.member) {
memoizedProperty(this, 'member', function() {
return Shape.create(shape.member, options);
});
}
if (this.flattened) {
var oldName = this.name;
memoizedProperty(this, 'name', function() {
return self.member.name || oldName;
});
}
}
function MapShape(shape, options) {
var firstInit = !this.isShape;
CompositeShape.apply(this, arguments);
if (firstInit) {
property(this, 'defaultValue', function() { return {}; });
property(this, 'key', Shape.create({type: 'string'}, options));
property(this, 'value', Shape.create({type: 'string'}, options));
}
if (shape.key) {
memoizedProperty(this, 'key', function() {
return Shape.create(shape.key, options);
});
}
if (shape.value) {
memoizedProperty(this, 'value', function() {
return Shape.create(shape.value, options);
});
}
}
function TimestampShape(shape) {
var self = this;
Shape.apply(this, arguments);
if (this.location === 'header') {
property(this, 'timestampFormat', 'rfc822');
} else if (shape.timestampFormat) {
property(this, 'timestampFormat', shape.timestampFormat);
} else if (this.api) {
if (this.api.timestampFormat) {
property(this, 'timestampFormat', this.api.timestampFormat);
} else {
switch (this.api.protocol) {
case 'json':
case 'rest-json':
property(this, 'timestampFormat', 'unixTimestamp');
break;
case 'rest-xml':
case 'query':
case 'ec2':
property(this, 'timestampFormat', 'iso8601');
break;
}
}
}
this.toType = function(value) {
if (value === null || value === undefined) return null;
if (typeof value.toUTCString === 'function') return value;
return typeof value === 'string' || typeof value === 'number' ?
util.date.parseTimestamp(value) : null;
};
this.toWireFormat = function(value) {
return util.date.format(value, self.timestampFormat);
};
}
function StringShape() {
Shape.apply(this, arguments);
if (this.api) {
switch (this.api.protocol) {
case 'rest-xml':
case 'query':
case 'ec2':
this.toType = function(value) { return value || ''; };
}
}
}
function FloatShape() {
Shape.apply(this, arguments);
this.toType = function(value) {
if (value === null || value === undefined) return null;
return parseFloat(value);
};
this.toWireFormat = this.toType;
}
function IntegerShape() {
Shape.apply(this, arguments);
this.toType = function(value) {
if (value === null || value === undefined) return null;
return parseInt(value, 10);
};
this.toWireFormat = this.toType;
}
function BinaryShape() {
Shape.apply(this, arguments);
this.toType = util.base64.decode;
this.toWireFormat = util.base64.encode;
}
function Base64Shape() {
BinaryShape.apply(this, arguments);
}
function BooleanShape() {
Shape.apply(this, arguments);
this.toType = function(value) {
if (typeof value === 'boolean') return value;
if (value === null || value === undefined) return null;
return value === 'true';
};
}
/**
* @api private
*/
Shape.shapes = {
StructureShape: StructureShape,
ListShape: ListShape,
MapShape: MapShape,
StringShape: StringShape,
BooleanShape: BooleanShape,
Base64Shape: Base64Shape
};
module.exports = Shape;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| json.js | 17.5% | (7 / 40) | 0% | (0 / 29) | 0% | (0 / 3) | 17.95% | (7 / 39) | |
| query.js | 15.38% | (8 / 52) | 0% | (0 / 29) | 0% | (0 / 4) | 16.67% | (8 / 48) | |
| rest.js | 9.64% | (8 / 83) | 0% | (0 / 48) | 0% | (0 / 17) | 9.88% | (8 / 81) | |
| rest_json.js | 24.39% | (10 / 41) | 0% | (0 / 18) | 0% | (0 / 4) | 25% | (10 / 40) | |
| rest_xml.js | 15.09% | (8 / 53) | 0% | (0 / 25) | 0% | (0 / 4) | 16% | (8 / 50) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | 1 1 1 1 1 1 1 | var util = require('../util');
var JsonBuilder = require('../json/builder');
var JsonParser = require('../json/parser');
function buildRequest(req) {
var httpRequest = req.httpRequest;
var api = req.service.api;
var target = api.targetPrefix + '.' + api.operations[req.operation].name;
var version = api.jsonVersion || '1.0';
var input = api.operations[req.operation].input;
var builder = new JsonBuilder();
if (version === 1) version = '1.0';
httpRequest.body = builder.build(req.params || {}, input);
httpRequest.headers['Content-Type'] = 'application/x-amz-json-' + version;
httpRequest.headers['X-Amz-Target'] = target;
}
function extractError(resp) {
var error = {};
var httpResponse = resp.httpResponse;
error.code = httpResponse.headers['x-amzn-errortype'] || 'UnknownError';
if (typeof error.code === 'string') {
error.code = error.code.split(':')[0];
}
if (httpResponse.body.length > 0) {
var e = JSON.parse(httpResponse.body.toString());
if (e.__type || e.code) {
error.code = (e.__type || e.code).split('#').pop();
}
if (error.code === 'RequestEntityTooLarge') {
error.message = 'Request body must be less than 1 MB';
} else {
error.message = (e.message || e.Message || null);
}
} else {
error.statusCode = httpResponse.statusCode;
error.message = httpResponse.statusCode.toString();
}
resp.error = util.error(new Error(), error);
}
function extractData(resp) {
var body = resp.httpResponse.body.toString() || '{}';
if (resp.request.service.config.convertResponseTypes === false) {
resp.data = JSON.parse(body);
} else {
var operation = resp.request.service.api.operations[resp.request.operation];
var shape = operation.output || {};
var parser = new JsonParser();
resp.data = parser.parse(body, shape);
}
}
module.exports = {
buildRequest: buildRequest,
extractError: extractError,
extractData: extractData
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | 1 1 1 1 1 1 1 1 | var AWS = require('../core');
var util = require('../util');
var QueryParamSerializer = require('../query/query_param_serializer');
var Shape = require('../model/shape');
function buildRequest(req) {
var operation = req.service.api.operations[req.operation];
var httpRequest = req.httpRequest;
httpRequest.headers['Content-Type'] =
'application/x-www-form-urlencoded; charset=utf-8';
httpRequest.params = {
Version: req.service.api.apiVersion,
Action: operation.name
};
// convert the request parameters into a list of query params,
// e.g. Deeply.NestedParam.0.Name=value
var builder = new QueryParamSerializer();
builder.serialize(req.params, operation.input, function(name, value) {
httpRequest.params[name] = value;
});
httpRequest.body = util.queryParamsToString(httpRequest.params);
}
function extractError(resp) {
var data, body = resp.httpResponse.body.toString();
if (body.match('<UnknownOperationException')) {
data = {
Code: 'UnknownOperation',
Message: 'Unknown operation ' + resp.request.operation
};
} else {
data = new AWS.XML.Parser().parse(body);
}
if (data.requestId && !resp.requestId) resp.requestId = data.requestId;
if (data.Errors) data = data.Errors;
if (data.Error) data = data.Error;
if (data.Code) {
resp.error = util.error(new Error(), {
code: data.Code,
message: data.Message
});
} else {
resp.error = util.error(new Error(), {
code: resp.httpResponse.statusCode,
message: null
});
}
}
function extractData(resp) {
var req = resp.request;
var operation = req.service.api.operations[req.operation];
var shape = operation.output || {};
var origRules = shape;
if (origRules.resultWrapper) {
var tmp = Shape.create({type: 'structure'});
tmp.members[origRules.resultWrapper] = shape;
tmp.memberNames = [origRules.resultWrapper];
util.property(shape, 'name', shape.resultWrapper);
shape = tmp;
}
var parser = new AWS.XML.Parser();
// TODO: Refactor XML Parser to parse RequestId from response.
if (shape && shape.members && !shape.members._XAMZRequestId) {
var requestIdShape = Shape.create(
{ type: 'string' },
{ api: { protocol: 'query' } },
'requestId'
);
shape.members._XAMZRequestId = requestIdShape;
}
var data = parser.parse(resp.httpResponse.body.toString(), shape);
resp.requestId = data._XAMZRequestId || data.requestId;
if (data._XAMZRequestId) delete data._XAMZRequestId;
if (origRules.resultWrapper) {
if (data[origRules.resultWrapper]) {
util.update(data, data[origRules.resultWrapper]);
delete data[origRules.resultWrapper];
}
}
resp.data = data;
}
module.exports = {
buildRequest: buildRequest,
extractError: extractError,
extractData: extractData
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | 1 1 1 1 1 1 1 1 | var util = require('../util');
function populateMethod(req) {
req.httpRequest.method = req.service.api.operations[req.operation].httpMethod;
}
function populateURI(req) {
var operation = req.service.api.operations[req.operation];
var input = operation.input;
var uri = [req.httpRequest.endpoint.path, operation.httpPath].join('/');
uri = uri.replace(/\/+/g, '/');
var queryString = {}, queryStringSet = false;
util.each(input.members, function (name, member) {
var paramValue = req.params[name];
if (paramValue === null || paramValue === undefined) return;
if (member.location === 'uri') {
var regex = new RegExp('\\{' + member.name + '(\\+)?\\}');
uri = uri.replace(regex, function(_, plus) {
var fn = plus ? util.uriEscapePath : util.uriEscape;
return fn(String(paramValue));
});
} else if (member.location === 'querystring') {
queryStringSet = true;
if (member.type === 'list') {
queryString[member.name] = paramValue.map(function(val) {
return util.uriEscape(String(val));
});
} else if (member.type === 'map') {
util.each(paramValue, function(key, value) {
if (Array.isArray(value)) {
queryString[key] = value.map(function(val) {
return util.uriEscape(String(val));
});
} else {
queryString[key] = util.uriEscape(String(value));
}
});
} else {
queryString[member.name] = util.uriEscape(String(paramValue));
}
}
});
if (queryStringSet) {
uri += (uri.indexOf('?') >= 0 ? '&' : '?');
var parts = [];
util.arrayEach(Object.keys(queryString).sort(), function(key) {
if (!Array.isArray(queryString[key])) {
queryString[key] = [queryString[key]];
}
for (var i = 0; i < queryString[key].length; i++) {
parts.push(util.uriEscape(String(key)) + '=' + queryString[key][i]);
}
});
uri += parts.join('&');
}
req.httpRequest.path = uri;
}
function populateHeaders(req) {
var operation = req.service.api.operations[req.operation];
util.each(operation.input.members, function (name, member) {
var value = req.params[name];
if (value === null || value === undefined) return;
if (member.location === 'headers' && member.type === 'map') {
util.each(value, function(key, memberValue) {
req.httpRequest.headers[member.name + key] = memberValue;
});
} else if (member.location === 'header') {
value = member.toWireFormat(value).toString();
req.httpRequest.headers[member.name] = value;
}
});
}
function buildRequest(req) {
populateMethod(req);
populateURI(req);
populateHeaders(req);
}
function extractError() {
}
function extractData(resp) {
var req = resp.request;
var data = {};
var r = resp.httpResponse;
var operation = req.service.api.operations[req.operation];
var output = operation.output;
// normalize headers names to lower-cased keys for matching
var headers = {};
util.each(r.headers, function (k, v) {
headers[k.toLowerCase()] = v;
});
util.each(output.members, function(name, member) {
var header = (member.name || name).toLowerCase();
if (member.location === 'headers' && member.type === 'map') {
data[name] = {};
var location = member.isLocationName ? member.name : '';
var pattern = new RegExp('^' + location + '(.+)', 'i');
util.each(r.headers, function (k, v) {
var result = k.match(pattern);
if (result !== null) {
data[name][result[1]] = v;
}
});
} else if (member.location === 'header') {
if (headers[header] !== undefined) {
data[name] = headers[header];
}
} else if (member.location === 'statusCode') {
data[name] = parseInt(r.statusCode, 10);
}
});
resp.data = data;
}
module.exports = {
buildRequest: buildRequest,
extractError: extractError,
extractData: extractData
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | 1 1 1 1 1 1 1 1 1 1 | var util = require('../util');
var Rest = require('./rest');
var Json = require('./json');
var JsonBuilder = require('../json/builder');
var JsonParser = require('../json/parser');
function populateBody(req) {
var builder = new JsonBuilder();
var input = req.service.api.operations[req.operation].input;
if (input.payload) {
var params = {};
var payloadShape = input.members[input.payload];
params = req.params[input.payload];
if (params === undefined) return;
if (payloadShape.type === 'structure') {
req.httpRequest.body = builder.build(params, payloadShape);
} else { // non-JSON payload
req.httpRequest.body = params;
}
} else {
req.httpRequest.body = builder.build(req.params, input);
}
}
function buildRequest(req) {
Rest.buildRequest(req);
// never send body payload on GET/HEAD/DELETE
if (['GET', 'HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) {
populateBody(req);
}
}
function extractError(resp) {
Json.extractError(resp);
}
function extractData(resp) {
Rest.extractData(resp);
var req = resp.request;
var rules = req.service.api.operations[req.operation].output || {};
if (rules.payload) {
var payloadMember = rules.members[rules.payload];
var body = resp.httpResponse.body;
if (payloadMember.isStreaming) {
resp.data[rules.payload] = body;
} else if (payloadMember.type === 'structure' || payloadMember.type === 'list') {
var parser = new JsonParser();
resp.data[rules.payload] = parser.parse(body, payloadMember);
} else {
resp.data[rules.payload] = body.toString();
}
} else {
var data = resp.data;
Json.extractData(resp);
resp.data = util.merge(data, resp.data);
}
}
module.exports = {
buildRequest: buildRequest,
extractError: extractError,
extractData: extractData
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | 1 1 1 1 1 1 1 1 | var AWS = require('../core');
var util = require('../util');
var Rest = require('./rest');
function populateBody(req) {
var input = req.service.api.operations[req.operation].input;
var builder = new AWS.XML.Builder();
var params = req.params;
var payload = input.payload;
if (payload) {
var payloadMember = input.members[payload];
params = params[payload];
if (params === undefined) return;
if (payloadMember.type === 'structure') {
var rootElement = payloadMember.name;
req.httpRequest.body = builder.toXML(params, payloadMember, rootElement, true);
} else { // non-xml payload
req.httpRequest.body = params;
}
} else {
req.httpRequest.body = builder.toXML(params, input, input.name ||
input.shape || util.string.upperFirst(req.operation) + 'Request');
}
}
function buildRequest(req) {
Rest.buildRequest(req);
// never send body payload on GET/HEAD
if (['GET', 'HEAD'].indexOf(req.httpRequest.method) < 0) {
populateBody(req);
}
}
function extractError(resp) {
Rest.extractError(resp);
var data = new AWS.XML.Parser().parse(resp.httpResponse.body.toString());
if (data.Errors) data = data.Errors;
if (data.Error) data = data.Error;
if (data.Code) {
resp.error = util.error(new Error(), {
code: data.Code,
message: data.Message
});
} else {
resp.error = util.error(new Error(), {
code: resp.httpResponse.statusCode,
message: null
});
}
}
function extractData(resp) {
Rest.extractData(resp);
var parser;
var req = resp.request;
var body = resp.httpResponse.body;
var operation = req.service.api.operations[req.operation];
var output = operation.output;
var payload = output.payload;
if (payload) {
var payloadMember = output.members[payload];
if (payloadMember.isStreaming) {
resp.data[payload] = body;
} else if (payloadMember.type === 'structure') {
parser = new AWS.XML.Parser();
resp.data[payload] = parser.parse(body.toString(), payloadMember);
} else {
resp.data[payload] = body.toString();
}
} else if (body.length > 0) {
parser = new AWS.XML.Parser();
var data = parser.parse(body.toString(), output);
util.update(resp.data, data);
}
}
module.exports = {
buildRequest: buildRequest,
extractError: extractError,
extractData: extractData
};
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| query_param_serializer.js | 16.98% | (9 / 53) | 0% | (0 / 36) | 0% | (0 / 10) | 17.65% | (9 / 51) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | 1 1 1 1 1 1 1 1 1 | var util = require('../util');
function QueryParamSerializer() {
}
QueryParamSerializer.prototype.serialize = function(params, shape, fn) {
serializeStructure('', params, shape, fn);
};
function ucfirst(shape) {
if (shape.isQueryName || shape.api.protocol !== 'ec2') {
return shape.name;
} else {
return shape.name[0].toUpperCase() + shape.name.substr(1);
}
}
function serializeStructure(prefix, struct, rules, fn) {
util.each(rules.members, function(name, member) {
var value = struct[name];
if (value === null || value === undefined) return;
var memberName = ucfirst(member);
memberName = prefix ? prefix + '.' + memberName : memberName;
serializeMember(memberName, value, member, fn);
});
}
function serializeMap(name, map, rules, fn) {
var i = 1;
util.each(map, function (key, value) {
var prefix = rules.flattened ? '.' : '.entry.';
var position = prefix + (i++) + '.';
var keyName = position + (rules.key.name || 'key');
var valueName = position + (rules.value.name || 'value');
serializeMember(name + keyName, key, rules.key, fn);
serializeMember(name + valueName, value, rules.value, fn);
});
}
function serializeList(name, list, rules, fn) {
var memberRules = rules.member || {};
if (list.length === 0) {
fn.call(this, name, null);
return;
}
util.arrayEach(list, function (v, n) {
var suffix = '.' + (n + 1);
if (rules.api.protocol === 'ec2') {
// Do nothing for EC2
suffix = suffix + ''; // make linter happy
} else if (rules.flattened) {
if (memberRules.name) {
var parts = name.split('.');
parts.pop();
parts.push(ucfirst(memberRules));
name = parts.join('.');
}
} else {
suffix = '.member' + suffix;
}
serializeMember(name + suffix, v, memberRules, fn);
});
}
function serializeMember(name, value, rules, fn) {
if (value === null || value === undefined) return;
if (rules.type === 'structure') {
serializeStructure(name, value, rules, fn);
} else if (rules.type === 'list') {
serializeList(name, value, rules, fn);
} else if (rules.type === 'map') {
serializeMap(name, value, rules, fn);
} else {
fn(name, rules.toWireFormat(value).toString());
}
}
module.exports = QueryParamSerializer;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| managed_upload.js | 2.34% | (5 / 214) | 0% | (0 / 111) | 0% | (0 / 26) | 2.5% | (5 / 200) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 | 1 1 1 1 1 | var AWS = require('../core');
var byteLength = AWS.util.string.byteLength;
/**
* The managed uploader allows for easy and efficient uploading of buffers,
* blobs, or streams, using a configurable amount of concurrency to perform
* multipart uploads where possible. This abstraction also enables uploading
* streams of unknown size due to the use of multipart uploads.
*
* To construct a managed upload object, see the {constructor} function.
*
* ## Tracking upload progress
*
* The managed upload object can also track progress by attaching an
* 'httpUploadProgress' listener to the upload manager. This event is similar
* to {AWS.Request~httpUploadProgress} but groups all concurrent upload progress
* into a single event. See {AWS.S3.ManagedUpload~httpUploadProgress} for more
* information.
*
* ## Handling Multipart Cleanup
*
* By default, this class will automatically clean up any multipart uploads
* when an individual part upload fails. This behavior can be disabled in order
* to manually handle failures by setting the `leavePartsOnError` configuration
* option to `true` when initializing the upload object.
*
* @!event httpUploadProgress(progress)
* Triggered when the uploader has uploaded more data.
* @note The `total` property may not be set if the stream being uploaded has
* not yet finished chunking. In this case the `total` will be undefined
* until the total stream size is known.
* @note This event will not be emitted in Node.js 0.8.x.
* @param progress [map] An object containing the `loaded` and `total` bytes
* of the request and the `key` of the S3 object. Note that `total` may be undefined until the payload
* size is known.
* @context (see AWS.Request~send)
*/
AWS.S3.ManagedUpload = AWS.util.inherit({
/**
* Creates a managed upload object with a set of configuration options.
*
* @note A "Body" parameter is required to be set prior to calling {send}.
* @option options params [map] a map of parameters to pass to the upload
* requests. The "Body" parameter is required to be specified either on
* the service or in the params option.
* @note ContentMD5 should not be provided when using the managed upload object.
* Instead, setting "computeChecksums" to true will enable automatic ContentMD5 generation
* by the managed upload object.
* @option options queueSize [Number] (4) the size of the concurrent queue
* manager to upload parts in parallel. Set to 1 for synchronous uploading
* of parts. Note that the uploader will buffer at most queueSize * partSize
* bytes into memory at any given time.
* @option options partSize [Number] (5mb) the size in bytes for each
* individual part to be uploaded. Adjust the part size to ensure the number
* of parts does not exceed {maxTotalParts}. See {minPartSize} for the
* minimum allowed part size.
* @option options leavePartsOnError [Boolean] (false) whether to abort the
* multipart upload if an error occurs. Set to true if you want to handle
* failures manually.
* @option options service [AWS.S3] an optional S3 service object to use for
* requests. This object might have bound parameters used by the uploader.
* @example Creating a default uploader for a stream object
* var upload = new AWS.S3.ManagedUpload({
* params: {Bucket: 'bucket', Key: 'key', Body: stream}
* });
* @example Creating an uploader with concurrency of 1 and partSize of 10mb
* var upload = new AWS.S3.ManagedUpload({
* partSize: 10 * 1024 * 1024, queueSize: 1,
* params: {Bucket: 'bucket', Key: 'key', Body: stream}
* });
* @see send
*/
constructor: function ManagedUpload(options) {
var self = this;
AWS.SequentialExecutor.call(self);
self.body = null;
self.sliceFn = null;
self.callback = null;
self.parts = {};
self.completeInfo = [];
self.fillQueue = function() {
self.callback(new Error('Unsupported body payload ' + typeof self.body));
};
self.configure(options);
},
/**
* @api private
*/
configure: function configure(options) {
options = options || {};
this.partSize = this.minPartSize;
if (options.queueSize) this.queueSize = options.queueSize;
if (options.partSize) this.partSize = options.partSize;
if (options.leavePartsOnError) this.leavePartsOnError = true;
if (this.partSize < this.minPartSize) {
throw new Error('partSize must be greater than ' +
this.minPartSize);
}
this.service = options.service;
this.bindServiceObject(options.params);
this.validateBody();
this.adjustTotalBytes();
},
/**
* @api private
*/
leavePartsOnError: false,
/**
* @api private
*/
queueSize: 4,
/**
* @api private
*/
partSize: null,
/**
* @readonly
* @return [Number] the minimum number of bytes for an individual part
* upload.
*/
minPartSize: 1024 * 1024 * 5,
/**
* @readonly
* @return [Number] the maximum allowed number of parts in a multipart upload.
*/
maxTotalParts: 10000,
/**
* Initiates the managed upload for the payload.
*
* @callback callback function(err, data)
* @param err [Error] an error or null if no error occurred.
* @param data [map] The response data from the successful upload:
* * `Location` (String) the URL of the uploaded object
* * `ETag` (String) the ETag of the uploaded object
* * `Bucket` (String) the bucket to which the object was uploaded
* * `Key` (String) the key to which the object was uploaded
* @example Sending a managed upload object
* var params = {Bucket: 'bucket', Key: 'key', Body: stream};
* var upload = new AWS.S3.ManagedUpload({params: params});
* upload.send(function(err, data) {
* console.log(err, data);
* });
*/
send: function(callback) {
var self = this;
self.failed = false;
self.callback = callback || function(err) { if (err) throw err; };
var runFill = true;
if (self.sliceFn) {
self.fillQueue = self.fillBuffer;
} else if (AWS.util.isNode()) {
var Stream = AWS.util.nodeRequire('stream').Stream;
if (self.body instanceof Stream) {
runFill = false;
self.fillQueue = self.fillStream;
self.partBuffers = [];
self.body.
on('readable', function() { self.fillQueue(); }).
on('end', function() {
self.isDoneChunking = true;
self.numParts = self.totalPartNumbers;
self.fillQueue.call(self);
});
}
}
if (runFill) self.fillQueue.call(self);
},
/**
* Aborts a managed upload, including all concurrent upload requests.
* @note By default, calling this function will cleanup a multipart upload
* if one was created. To leave the multipart upload around after aborting
* a request, configure `leavePartsOnError` to `true` in the {constructor}.
* @note Calling {abort} in the browser environment will not abort any requests
* that are already in flight. If a multipart upload was created, any parts
* not yet uploaded will not be sent, and the multipart upload will be cleaned up.
* @example Aborting an upload
* var params = {
* Bucket: 'bucket', Key: 'key',
* Body: new Buffer(1024 * 1024 * 25) // 25MB payload
* };
* var upload = s3.upload(params);
* upload.send(function (err, data) {
* if (err) console.log("Error:", err.code, err.message);
* else console.log(data);
* });
*
* // abort request in 1 second
* setTimeout(upload.abort.bind(upload), 1000);
*/
abort: function() {
this.cleanup(AWS.util.error(new Error('Request aborted by user'), {
code: 'RequestAbortedError', retryable: false
}));
},
/**
* @api private
*/
validateBody: function validateBody() {
var self = this;
self.body = self.service.config.params.Body;
if (!self.body) throw new Error('params.Body is required');
if (typeof self.body === 'string') {
self.body = new AWS.util.Buffer(self.body);
}
self.sliceFn = AWS.util.arraySliceFn(self.body);
},
/**
* @api private
*/
bindServiceObject: function bindServiceObject(params) {
params = params || {};
var self = this;
// bind parameters to new service object
if (!self.service) {
self.service = new AWS.S3({params: params});
} else {
var config = AWS.util.copy(self.service.config);
self.service = new self.service.constructor.__super__(config);
self.service.config.params =
AWS.util.merge(self.service.config.params || {}, params);
}
},
/**
* @api private
*/
adjustTotalBytes: function adjustTotalBytes() {
var self = this;
try { // try to get totalBytes
self.totalBytes = byteLength(self.body);
} catch (e) { }
// try to adjust partSize if we know payload length
if (self.totalBytes) {
var newPartSize = Math.ceil(self.totalBytes / self.maxTotalParts);
if (newPartSize > self.partSize) self.partSize = newPartSize;
} else {
self.totalBytes = undefined;
}
},
/**
* @api private
*/
isDoneChunking: false,
/**
* @api private
*/
partPos: 0,
/**
* @api private
*/
totalChunkedBytes: 0,
/**
* @api private
*/
totalUploadedBytes: 0,
/**
* @api private
*/
totalBytes: undefined,
/**
* @api private
*/
numParts: 0,
/**
* @api private
*/
totalPartNumbers: 0,
/**
* @api private
*/
activeParts: 0,
/**
* @api private
*/
doneParts: 0,
/**
* @api private
*/
parts: null,
/**
* @api private
*/
completeInfo: null,
/**
* @api private
*/
failed: false,
/**
* @api private
*/
multipartReq: null,
/**
* @api private
*/
partBuffers: null,
/**
* @api private
*/
partBufferLength: 0,
/**
* @api private
*/
fillBuffer: function fillBuffer() {
var self = this;
var bodyLen = byteLength(self.body);
if (bodyLen === 0) {
self.isDoneChunking = true;
self.numParts = 1;
self.nextChunk(self.body);
return;
}
while (self.activeParts < self.queueSize && self.partPos < bodyLen) {
var endPos = Math.min(self.partPos + self.partSize, bodyLen);
var buf = self.sliceFn.call(self.body, self.partPos, endPos);
self.partPos += self.partSize;
if (byteLength(buf) < self.partSize || self.partPos === bodyLen) {
self.isDoneChunking = true;
self.numParts = self.totalPartNumbers + 1;
}
self.nextChunk(buf);
}
},
/**
* @api private
*/
fillStream: function fillStream() {
var self = this;
if (self.activeParts >= self.queueSize) return;
var buf = self.body.read(self.partSize - self.partBufferLength) ||
self.body.read();
if (buf) {
self.partBuffers.push(buf);
self.partBufferLength += buf.length;
self.totalChunkedBytes += buf.length;
}
if (self.partBufferLength >= self.partSize) {
// if we have single buffer we avoid copyfull concat
var pbuf = self.partBuffers.length === 1 ?
self.partBuffers[0] : Buffer.concat(self.partBuffers);
self.partBuffers = [];
self.partBufferLength = 0;
// if we have more than partSize, push the rest back on the queue
if (pbuf.length > self.partSize) {
var rest = pbuf.slice(self.partSize);
self.partBuffers.push(rest);
self.partBufferLength += rest.length;
pbuf = pbuf.slice(0, self.partSize);
}
self.nextChunk(pbuf);
}
if (self.isDoneChunking && !self.isDoneSending) {
// if we have single buffer we avoid copyfull concat
pbuf = self.partBuffers.length === 1 ?
self.partBuffers[0] : Buffer.concat(self.partBuffers);
self.partBuffers = [];
self.partBufferLength = 0;
self.totalBytes = self.totalChunkedBytes;
self.isDoneSending = true;
if (self.numParts === 0 || pbuf.length > 0) {
self.numParts++;
self.nextChunk(pbuf);
}
}
self.body.read(0);
},
/**
* @api private
*/
nextChunk: function nextChunk(chunk) {
var self = this;
if (self.failed) return null;
var partNumber = ++self.totalPartNumbers;
if (self.isDoneChunking && partNumber === 1) {
var req = self.service.putObject({Body: chunk});
req._managedUpload = self;
req.on('httpUploadProgress', self.progress).send(self.finishSinglePart);
return null;
} else if (self.service.config.params.ContentMD5) {
var err = AWS.util.error(new Error('The Content-MD5 you specified is invalid for multi-part uploads.'), {
code: 'InvalidDigest', retryable: false
});
self.cleanup(err);
return null;
}
if (self.completeInfo[partNumber] && self.completeInfo[partNumber].ETag !== null) {
return null; // Already uploaded this part.
}
self.activeParts++;
if (!self.service.config.params.UploadId) {
if (!self.multipartReq) { // create multipart
self.multipartReq = self.service.createMultipartUpload();
self.multipartReq.on('success', function(resp) {
self.service.config.params.UploadId = resp.data.UploadId;
self.multipartReq = null;
});
self.queueChunks(chunk, partNumber);
self.multipartReq.on('error', function(err) {
self.cleanup(err);
});
self.multipartReq.send();
} else {
self.queueChunks(chunk, partNumber);
}
} else { // multipart is created, just send
self.uploadPart(chunk, partNumber);
}
},
/**
* @api private
*/
uploadPart: function uploadPart(chunk, partNumber) {
var self = this;
var partParams = {
Body: chunk,
ContentLength: AWS.util.string.byteLength(chunk),
PartNumber: partNumber
};
var partInfo = {ETag: null, PartNumber: partNumber};
self.completeInfo[partNumber] = partInfo;
var req = self.service.uploadPart(partParams);
self.parts[partNumber] = req;
req._lastUploadedBytes = 0;
req._managedUpload = self;
req.on('httpUploadProgress', self.progress);
req.send(function(err, data) {
delete self.parts[partParams.PartNumber];
self.activeParts--;
if (!err && (!data || !data.ETag)) {
var message = 'No access to ETag property on response.';
if (AWS.util.isBrowser()) {
message += ' Check CORS configuration to expose ETag header.';
}
err = AWS.util.error(new Error(message), {
code: 'ETagMissing', retryable: false
});
}
if (err) return self.cleanup(err);
partInfo.ETag = data.ETag;
self.doneParts++;
if (self.isDoneChunking && self.doneParts === self.numParts) {
self.finishMultiPart();
} else {
self.fillQueue.call(self);
}
});
},
/**
* @api private
*/
queueChunks: function queueChunks(chunk, partNumber) {
var self = this;
self.multipartReq.on('success', function() {
self.uploadPart(chunk, partNumber);
});
},
/**
* @api private
*/
cleanup: function cleanup(err) {
var self = this;
if (self.failed) return;
// clean up stream
if (typeof self.body.removeAllListeners === 'function' &&
typeof self.body.resume === 'function') {
self.body.removeAllListeners('readable');
self.body.removeAllListeners('end');
self.body.resume();
}
if (self.service.config.params.UploadId && !self.leavePartsOnError) {
self.service.abortMultipartUpload().send();
}
AWS.util.each(self.parts, function(partNumber, part) {
part.removeAllListeners('complete');
part.abort();
});
self.activeParts = 0;
self.partPos = 0;
self.numParts = 0;
self.totalPartNumbers = 0;
self.parts = {};
self.failed = true;
self.callback(err);
},
/**
* @api private
*/
finishMultiPart: function finishMultiPart() {
var self = this;
var completeParams = { MultipartUpload: { Parts: self.completeInfo.slice(1) } };
self.service.completeMultipartUpload(completeParams, function(err, data) {
if (err) return self.cleanup(err);
else self.callback(err, data);
});
},
/**
* @api private
*/
finishSinglePart: function finishSinglePart(err, data) {
var upload = this.request._managedUpload;
var httpReq = this.request.httpRequest;
var endpoint = httpReq.endpoint;
if (err) return upload.callback(err);
data.Location =
[endpoint.protocol, '//', endpoint.host, httpReq.path].join('');
data.key = this.request.params.Key; // will stay undocumented
data.Key = this.request.params.Key;
data.Bucket = this.request.params.Bucket;
upload.callback(err, data);
},
/**
* @api private
*/
progress: function progress(info) {
var upload = this._managedUpload;
if (this.operation === 'putObject') {
info.part = 1;
info.key = this.params.Key;
} else {
upload.totalUploadedBytes += info.loaded - this._lastUploadedBytes;
this._lastUploadedBytes = info.loaded;
info = {
loaded: upload.totalUploadedBytes,
total: upload.totalBytes,
part: this.params.PartNumber,
key: this.params.Key
};
}
upload.emit('httpUploadProgress', [info]);
}
});
AWS.util.mixin(AWS.S3.ManagedUpload, AWS.SequentialExecutor);
module.exports = AWS.S3.ManagedUpload;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| apigateway.js | 15.38% | (2 / 13) | 0% | (0 / 6) | 0% | (0 / 3) | 15.38% | (2 / 13) | |
| cloudfront.js | 75% | (3 / 4) | 100% | (0 / 0) | 0% | (0 / 1) | 75% | (3 / 4) | |
| cloudsearchdomain.js | 7.69% | (2 / 26) | 0% | (0 / 12) | 0% | (0 / 6) | 8% | (2 / 25) | |
| cognitoidentity.js | 40% | (2 / 5) | 100% | (0 / 0) | 0% | (0 / 3) | 40% | (2 / 5) | |
| dynamodb.js | 16.67% | (3 / 18) | 0% | (0 / 10) | 0% | (0 / 4) | 17.65% | (3 / 17) | |
| ec2.js | 7.41% | (2 / 27) | 0% | (0 / 14) | 0% | (0 / 4) | 7.69% | (2 / 26) | |
| glacier.js | 4.88% | (2 / 41) | 0% | (0 / 12) | 0% | (0 / 6) | 5.26% | (2 / 38) | |
| iotdata.js | 20% | (2 / 10) | 0% | (0 / 10) | 0% | (0 / 3) | 20% | (2 / 10) | |
| machinelearning.js | 28.57% | (2 / 7) | 0% | (0 / 4) | 0% | (0 / 2) | 28.57% | (2 / 7) | |
| route53.js | 40% | (2 / 5) | 100% | (0 / 0) | 0% | (0 / 2) | 40% | (2 / 5) | |
| s3.js | 1.56% | (5 / 321) | 0% | (0 / 331) | 0% | (0 / 36) | 1.6% | (5 / 312) | |
| sqs.js | 3.64% | (2 / 55) | 0% | (0 / 30) | 0% | (0 / 11) | 3.92% | (2 / 51) | |
| sts.js | 14.29% | (2 / 14) | 0% | (0 / 4) | 0% | (0 / 3) | 16.67% | (2 / 12) | |
| swf.js | 100% | (3 / 3) | 100% | (0 / 0) | 100% | (0 / 0) | 100% | (3 / 3) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 1 1 | var AWS = require('../core');
AWS.util.update(AWS.APIGateway.prototype, {
/**
* Sets the Accept header to application/json.
*
* @api private
*/
setAcceptHeader: function setAcceptHeader(req) {
var httpRequest = req.httpRequest;
httpRequest.headers['Accept'] = 'application/json';
},
/**
* @api private
*/
setupRequestListeners: function setupRequestListeners(request) {
request.addListener('build', this.setAcceptHeader);
if (request.operation === 'getSdk') {
request.addListener('extractData', this.useRawPayload);
}
},
useRawPayload: function useRawPayload(resp) {
var req = resp.request;
var operation = req.operation;
var rules = req.service.api.operations[operation].output || {};
if (rules.payload) {
var body = resp.httpResponse.body;
resp.data[rules.payload] = body;
}
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 1 1 1 | var AWS = require('../core');
// pull in CloudFront signer
require('../cloudfront/signer');
AWS.util.update(AWS.CloudFront.prototype, {
setupRequestListeners: function setupRequestListeners(request) {
request.addListener('extractData', AWS.util.hoistPayloadMember);
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | 1 1 | var AWS = require('../core');
/**
* Constructs a service interface object. Each API operation is exposed as a
* function on service.
*
* ### Sending a Request Using CloudSearchDomain
*
* ```javascript
* var csd = new AWS.CloudSearchDomain({endpoint: 'my.host.tld'});
* csd.search(params, function (err, data) {
* if (err) console.log(err, err.stack); // an error occurred
* else console.log(data); // successful response
* });
* ```
*
* ### Locking the API Version
*
* In order to ensure that the CloudSearchDomain object uses this specific API,
* you can construct the object by passing the `apiVersion` option to the
* constructor:
*
* ```javascript
* var csd = new AWS.CloudSearchDomain({
* endpoint: 'my.host.tld',
* apiVersion: '2013-01-01'
* });
* ```
*
* You can also set the API version globally in `AWS.config.apiVersions` using
* the **cloudsearchdomain** service identifier:
*
* ```javascript
* AWS.config.apiVersions = {
* cloudsearchdomain: '2013-01-01',
* // other service API versions
* };
*
* var csd = new AWS.CloudSearchDomain({endpoint: 'my.host.tld'});
* ```
*
* @note You *must* provide an `endpoint` configuration parameter when
* constructing this service. See {constructor} for more information.
*
* @!method constructor(options = {})
* Constructs a service object. This object has one method for each
* API operation.
*
* @example Constructing a CloudSearchDomain object
* var csd = new AWS.CloudSearchDomain({endpoint: 'my.host.tld'});
* @note You *must* provide an `endpoint` when constructing this service.
* @option (see AWS.Config.constructor)
*
* @service cloudsearchdomain
* @version 2013-01-01
*/
AWS.util.update(AWS.CloudSearchDomain.prototype, {
/**
* @api private
*/
validateService: function validateService() {
if (!this.config.endpoint || this.config.endpoint.indexOf('{') >= 0) {
var msg = 'AWS.CloudSearchDomain requires an explicit ' +
'`endpoint\' configuration option.';
throw AWS.util.error(new Error(),
{name: 'InvalidEndpoint', message: msg});
}
},
/**
* @api private
*/
setupRequestListeners: function setupRequestListeners(request) {
request.removeListener('validate',
AWS.EventListeners.Core.VALIDATE_CREDENTIALS
);
request.onAsync('validate', this.validateCredentials);
request.addListener('validate', this.updateRegion);
if (request.operation === 'search') {
request.addListener('build', this.convertGetToPost);
}
},
/**
* @api private
*/
validateCredentials: function(req, done) {
if (!req.service.api.signatureVersion) return done(); // none
req.service.config.getCredentials(function(err) {
if (err) {
req.removeListener('sign', AWS.EventListeners.Core.SIGN);
}
done();
});
},
/**
* @api private
*/
convertGetToPost: function(request) {
var httpRequest = request.httpRequest
// convert queries to POST to avoid length restrictions
var path = httpRequest.path.split('?')
httpRequest.method = 'POST'
httpRequest.path = path[0]
httpRequest.body = path[1]
httpRequest.headers['Content-Length'] = httpRequest.body.length
httpRequest.headers['Content-Type'] = 'application/x-www-form-urlencoded'
},
/**
* @api private
*/
updateRegion: function updateRegion(request) {
var endpoint = request.httpRequest.endpoint.hostname;
var zones = endpoint.split('.');
request.httpRequest.region = zones[1] || request.httpRequest.region;
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 1 1 | var AWS = require('../core');
AWS.util.update(AWS.CognitoIdentity.prototype, {
getOpenIdToken: function getOpenIdToken(params, callback) {
return this.makeUnauthenticatedRequest('getOpenIdToken', params, callback);
},
getId: function getId(params, callback) {
return this.makeUnauthenticatedRequest('getId', params, callback);
},
getCredentialsForIdentity: function getCredentialsForIdentity(params, callback) {
return this.makeUnauthenticatedRequest('getCredentialsForIdentity', params, callback);
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 1 1 1 | var AWS = require('../core');
require('../dynamodb/document_client');
AWS.util.update(AWS.DynamoDB.prototype, {
/**
* @api private
*/
setupRequestListeners: function setupRequestListeners(request) {
if (request.service.config.dynamoDbCrc32) {
request.removeListener('extractData', AWS.EventListeners.Json.EXTRACT_DATA);
request.addListener('extractData', this.checkCrc32);
request.addListener('extractData', AWS.EventListeners.Json.EXTRACT_DATA);
}
},
/**
* @api private
*/
checkCrc32: function checkCrc32(resp) {
if (!resp.httpResponse.streaming && !resp.request.service.crc32IsValid(resp)) {
resp.data = null;
resp.error = AWS.util.error(new Error(), {
code: 'CRC32CheckFailed',
message: 'CRC32 integrity check failed',
retryable: true
});
resp.request.haltHandlersOnError();
throw (resp.error);
}
},
/**
* @api private
*/
crc32IsValid: function crc32IsValid(resp) {
var crc = resp.httpResponse.headers['x-amz-crc32'];
if (!crc) return true; // no (valid) CRC32 header
return parseInt(crc, 10) === AWS.util.crypto.crc32(resp.httpResponse.body);
},
/**
* @api private
*/
defaultRetryCount: 10,
/**
* @api private
*/
retryDelays: function retryDelays(retryCount) {
var delay = retryCount > 0 ? (50 * Math.pow(2, retryCount - 1)) : 0;
return delay;
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | 1 1 | var AWS = require('../core');
AWS.util.update(AWS.EC2.prototype, {
/**
* @api private
*/
setupRequestListeners: function setupRequestListeners(request) {
request.removeListener('extractError', AWS.EventListeners.Query.EXTRACT_ERROR);
request.addListener('extractError', this.extractError);
if (request.operation === 'copySnapshot') {
request.onAsync('validate', this.buildCopySnapshotPresignedUrl);
}
},
/**
* @api private
*/
buildCopySnapshotPresignedUrl: function buildCopySnapshotPresignedUrl(req, done) {
if (req.params.PresignedUrl || req._subRequest) {
return done();
}
req.params = AWS.util.copy(req.params);
req.params.DestinationRegion = req.service.config.region;
var config = AWS.util.copy(req.service.config);
delete config.endpoint;
config.region = req.params.SourceRegion;
var svc = new req.service.constructor(config);
var newReq = svc[req.operation](req.params);
newReq._subRequest = true;
newReq.presign(function(err, url) {
if (err) done(err);
else {
req.params.PresignedUrl = url;
done();
}
});
},
/**
* @api private
*/
extractError: function extractError(resp) {
// EC2 nests the error code and message deeper than other AWS Query services.
var httpResponse = resp.httpResponse;
var data = new AWS.XML.Parser().parse(httpResponse.body.toString() || '');
if (data.Errors) {
resp.error = AWS.util.error(new Error(), {
code: data.Errors.Error.Code,
message: data.Errors.Error.Message
});
} else {
resp.error = AWS.util.error(new Error(), {
code: httpResponse.statusCode,
message: null
});
}
resp.error.requestId = data.RequestID || null;
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | 1 1 | var AWS = require('../core');
AWS.util.update(AWS.Glacier.prototype, {
/**
* @api private
*/
setupRequestListeners: function setupRequestListeners(request) {
if (Array.isArray(request._events.validate)) {
request._events.validate.unshift(this.validateAccountId);
} else {
request.on('validate', this.validateAccountId);
}
request.removeListener('afterBuild',
AWS.EventListeners.Core.COMPUTE_SHA256);
request.on('build', this.addGlacierApiVersion);
request.on('build', this.addTreeHashHeaders);
},
/**
* @api private
*/
validateAccountId: function validateAccountId(request) {
if (request.params.accountId !== undefined) return;
request.params = AWS.util.copy(request.params);
request.params.accountId = '-';
},
/**
* @api private
*/
addGlacierApiVersion: function addGlacierApiVersion(request) {
var version = request.service.api.apiVersion;
request.httpRequest.headers['x-amz-glacier-version'] = version;
},
/**
* @api private
*/
addTreeHashHeaders: function addTreeHashHeaders(request) {
if (request.params.body === undefined) return;
var hashes = request.service.computeChecksums(request.params.body);
request.httpRequest.headers['X-Amz-Content-Sha256'] = hashes.linearHash;
if (!request.httpRequest.headers['x-amz-sha256-tree-hash']) {
request.httpRequest.headers['x-amz-sha256-tree-hash'] = hashes.treeHash;
}
},
/**
* @!group Computing Checksums
*/
/**
* Computes the SHA-256 linear and tree hash checksums for a given
* block of Buffer data. Pass the tree hash of the computed checksums
* as the checksum input to the {completeMultipartUpload} when performing
* a multi-part upload.
*
* @example Calculate checksum of 5.5MB data chunk
* var glacier = new AWS.Glacier();
* var data = new Buffer(5.5 * 1024 * 1024);
* data.fill('0'); // fill with zeros
* var results = glacier.computeChecksums(data);
* // Result: { linearHash: '68aff0c5a9...', treeHash: '154e26c78f...' }
* @param data [Buffer, String] data to calculate the checksum for
* @return [map<linearHash:String,treeHash:String>] a map containing
* the linearHash and treeHash properties representing hex based digests
* of the respective checksums.
* @see completeMultipartUpload
*/
computeChecksums: function computeChecksums(data) {
if (!AWS.util.Buffer.isBuffer(data)) data = new AWS.util.Buffer(data);
var mb = 1024 * 1024;
var hashes = [];
var hash = AWS.util.crypto.createHash('sha256');
// build leaf nodes in 1mb chunks
for (var i = 0; i < data.length; i += mb) {
var chunk = data.slice(i, Math.min(i + mb, data.length));
hash.update(chunk);
hashes.push(AWS.util.crypto.sha256(chunk));
}
return {
linearHash: hash.digest('hex'),
treeHash: this.buildHashTree(hashes)
};
},
/**
* @api private
*/
buildHashTree: function buildHashTree(hashes) {
// merge leaf nodes
while (hashes.length > 1) {
var tmpHashes = [];
for (var i = 0; i < hashes.length; i += 2) {
if (hashes[i + 1]) {
var tmpHash = new AWS.util.Buffer(64);
tmpHash.write(hashes[i], 0, 32, 'binary');
tmpHash.write(hashes[i + 1], 32, 32, 'binary');
tmpHashes.push(AWS.util.crypto.sha256(tmpHash));
} else {
tmpHashes.push(hashes[i]);
}
}
hashes = tmpHashes;
}
return AWS.util.crypto.toHex(hashes[0]);
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | 1 1 | var AWS = require('../core');
/**
* Constructs a service interface object. Each API operation is exposed as a
* function on service.
*
* ### Sending a Request Using IotData
*
* ```javascript
* var iotdata = new AWS.IotData({endpoint: 'my.host.tld'});
* iotdata.getThingShadow(params, function (err, data) {
* if (err) console.log(err, err.stack); // an error occurred
* else console.log(data); // successful response
* });
* ```
*
* ### Locking the API Version
*
* In order to ensure that the IotData object uses this specific API,
* you can construct the object by passing the `apiVersion` option to the
* constructor:
*
* ```javascript
* var iotdata = new AWS.IotData({
* endpoint: 'my.host.tld',
* apiVersion: '2015-05-28'
* });
* ```
*
* You can also set the API version globally in `AWS.config.apiVersions` using
* the **iotdata** service identifier:
*
* ```javascript
* AWS.config.apiVersions = {
* iotdata: '2015-05-28',
* // other service API versions
* };
*
* var iotdata = new AWS.IotData({endpoint: 'my.host.tld'});
* ```
*
* @note You *must* provide an `endpoint` configuration parameter when
* constructing this service. See {constructor} for more information.
*
* @!method constructor(options = {})
* Constructs a service object. This object has one method for each
* API operation.
*
* @example Constructing a IotData object
* var iotdata = new AWS.IotData({endpoint: 'my.host.tld'});
* @note You *must* provide an `endpoint` when constructing this service.
* @option (see AWS.Config.constructor)
*
* @service iotdata
* @version 2015-05-28
*/
AWS.util.update(AWS.IotData.prototype, {
/**
* @api private
*/
validateService: function validateService() {
if (!this.config.endpoint || this.config.endpoint.indexOf('{') >= 0) {
var msg = 'AWS.IotData requires an explicit ' +
'`endpoint\' configuration option.';
throw AWS.util.error(new Error(),
{name: 'InvalidEndpoint', message: msg});
}
},
/**
* @api private
*/
setupRequestListeners: function setupRequestListeners(request) {
request.addListener('validateResponse', this.validateResponseBody)
},
/**
* @api private
*/
validateResponseBody: function validateResponseBody(resp) {
var body = resp.httpResponse.body.toString() || '{}';
var bodyCheck = body.trim();
if (!bodyCheck || bodyCheck.charAt(0) !== '{') {
resp.httpResponse.body = '';
}
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 1 1 | var AWS = require('../core');
AWS.util.update(AWS.MachineLearning.prototype, {
/**
* @api private
*/
setupRequestListeners: function setupRequestListeners(request) {
if (request.operation === 'predict') {
request.addListener('build', this.buildEndpoint);
}
},
/**
* Updates request endpoint from PredictEndpoint
* @api private
*/
buildEndpoint: function buildEndpoint(request) {
var url = request.params.PredictEndpoint;
if (url) {
request.httpRequest.endpoint = new AWS.Endpoint(url);
}
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 1 1 | var AWS = require('../core');
AWS.util.update(AWS.Route53.prototype, {
/**
* @api private
*/
setupRequestListeners: function setupRequestListeners(request) {
request.on('build', this.sanitizeUrl);
},
/**
* @api private
*/
sanitizeUrl: function sanitizeUrl(request) {
var path = request.httpRequest.path;
request.httpRequest.path = path.replace(/\/%2F\w+%2F/, '/');
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 | 1 1 1 1 1 | var AWS = require('../core');
// Pull in managed upload extension
require('../s3/managed_upload');
/**
* @api private
*/
var operationsWith200StatusCodeError = {
'completeMultipartUpload': true,
'copyObject': true,
'uploadPartCopy': true
};
/**
* @api private
*/
var regionRedirectErrorCodes = [
'AuthorizationHeaderMalformed', // non-head operations on virtual-hosted global bucket endpoints
'BadRequest', // head operations on virtual-hosted global bucket endpoints
'PermanentRedirect', // non-head operations on path-style or regional endpoints
301 // head operations on path-style or regional endpoints
];
AWS.util.update(AWS.S3.prototype, {
/**
* @api private
*/
getSignerClass: function getSignerClass(request) {
var defaultApiVersion = this.api.signatureVersion;
var userDefinedVersion = this._originalConfig ? this._originalConfig.signatureVersion : null;
var regionDefinedVersion = this.config.signatureVersion;
var isPresigned = request ? request.isPresigned() : false;
/*
1) User defined version specified:
a) always return user defined version
2) No user defined version specified:
a) default to lowest version the region supports
*/
if (userDefinedVersion) {
userDefinedVersion = userDefinedVersion === 'v2' ? 's3' : userDefinedVersion;
return AWS.Signers.RequestSigner.getVersion(userDefinedVersion);
}
if (regionDefinedVersion) {
defaultApiVersion = regionDefinedVersion;
}
return AWS.Signers.RequestSigner.getVersion(defaultApiVersion);
},
/**
* @api private
*/
validateService: function validateService() {
var msg;
var messages = [];
// default to us-east-1 when no region is provided
if (!this.config.region) this.config.region = 'us-east-1';
if (!this.config.endpoint && this.config.s3BucketEndpoint) {
messages.push('An endpoint must be provided when configuring ' +
'`s3BucketEndpoint` to true.');
}
if (this.config.useAccelerateEndpoint && this.config.useDualstack) {
messages.push('`useAccelerateEndpoint` and `useDualstack` ' +
'cannot both be configured to true.');
}
if (messages.length === 1) {
msg = messages[0];
} else if (messages.length > 1) {
msg = 'Multiple configuration errors:\n' + messages.join('\n');
}
if (msg) {
throw AWS.util.error(new Error(),
{name: 'InvalidEndpoint', message: msg});
}
},
/**
* @api private
*/
shouldDisableBodySigning: function shouldDisableBodySigning(request) {
var signerClass = this.getSignerClass();
if (this.config.s3DisableBodySigning === true && signerClass === AWS.Signers.V4
&& request.httpRequest.endpoint.protocol === 'https:') {
return true;
}
return false;
},
/**
* @api private
*/
setupRequestListeners: function setupRequestListeners(request) {
request.addListener('validate', this.validateScheme);
request.addListener('validate', this.validateBucketEndpoint);
request.addListener('validate', this.correctBucketRegionFromCache);
request.addListener('build', this.addContentType);
request.addListener('build', this.populateURI);
request.addListener('build', this.computeContentMd5);
request.addListener('build', this.computeSseCustomerKeyMd5);
request.addListener('afterBuild', this.addExpect100Continue);
request.removeListener('validate',
AWS.EventListeners.Core.VALIDATE_REGION);
request.addListener('extractError', this.extractError);
request.onAsync('extractError', this.requestBucketRegion);
request.addListener('extractData', this.extractData);
request.addListener('extractData', AWS.util.hoistPayloadMember);
request.addListener('beforePresign', this.prepareSignedUrl);
if (AWS.util.isBrowser()) {
request.onAsync('retry', this.reqRegionForNetworkingError);
}
if (this.shouldDisableBodySigning(request)) {
request.removeListener('afterBuild', AWS.EventListeners.Core.COMPUTE_SHA256);
request.addListener('afterBuild', this.disableBodySigning);
}
},
/**
* @api private
*/
validateScheme: function(req) {
var params = req.params,
scheme = req.httpRequest.endpoint.protocol,
sensitive = params.SSECustomerKey || params.CopySourceSSECustomerKey;
if (sensitive && scheme !== 'https:') {
var msg = 'Cannot send SSE keys over HTTP. Set \'sslEnabled\'' +
'to \'true\' in your configuration';
throw AWS.util.error(new Error(),
{ code: 'ConfigError', message: msg });
}
},
/**
* @api private
*/
validateBucketEndpoint: function(req) {
if (!req.params.Bucket && req.service.config.s3BucketEndpoint) {
var msg = 'Cannot send requests to root API with `s3BucketEndpoint` set.';
throw AWS.util.error(new Error(),
{ code: 'ConfigError', message: msg });
}
},
/**
* @api private
*/
isValidAccelerateOperation: function isValidAccelerateOperation(operation) {
var invalidOperations = [
'createBucket',
'deleteBucket',
'listBuckets'
];
return invalidOperations.indexOf(operation) === -1;
},
/**
* S3 prefers dns-compatible bucket names to be moved from the uri path
* to the hostname as a sub-domain. This is not possible, even for dns-compat
* buckets when using SSL and the bucket name contains a dot ('.'). The
* ssl wildcard certificate is only 1-level deep.
*
* @api private
*/
populateURI: function populateURI(req) {
var httpRequest = req.httpRequest;
var b = req.params.Bucket;
var service = req.service;
var endpoint = httpRequest.endpoint;
if (b) {
if (!service.pathStyleBucketName(b)) {
if (service.config.useAccelerateEndpoint && service.isValidAccelerateOperation(req.operation)) {
endpoint.hostname = b + '.s3-accelerate.amazonaws.com';
} else if (!service.config.s3BucketEndpoint) {
endpoint.hostname =
b + '.' + endpoint.hostname;
}
var port = endpoint.port;
if (port !== 80 && port !== 443) {
endpoint.host = endpoint.hostname + ':' +
endpoint.port;
} else {
endpoint.host = endpoint.hostname;
}
httpRequest.virtualHostedBucket = b; // needed for signing the request
service.removeVirtualHostedBucketFromPath(req);
}
}
},
/**
* Takes the bucket name out of the path if bucket is virtual-hosted
*
* @api private
*/
removeVirtualHostedBucketFromPath: function removeVirtualHostedBucketFromPath(req) {
var httpRequest = req.httpRequest;
var bucket = httpRequest.virtualHostedBucket;
if (bucket && httpRequest.path) {
httpRequest.path = httpRequest.path.replace(new RegExp('/' + bucket), '');
if (httpRequest.path[0] !== '/') {
httpRequest.path = '/' + httpRequest.path;
}
}
},
/**
* Adds Expect: 100-continue header if payload is greater-or-equal 1MB
* @api private
*/
addExpect100Continue: function addExpect100Continue(req) {
var len = req.httpRequest.headers['Content-Length'];
if (AWS.util.isNode() && len >= 1024 * 1024) {
req.httpRequest.headers['Expect'] = '100-continue';
}
},
/**
* Adds a default content type if none is supplied.
*
* @api private
*/
addContentType: function addContentType(req) {
var httpRequest = req.httpRequest;
if (httpRequest.method === 'GET' || httpRequest.method === 'HEAD') {
// Content-Type is not set in GET/HEAD requests
delete httpRequest.headers['Content-Type'];
return;
}
if (!httpRequest.headers['Content-Type']) { // always have a Content-Type
httpRequest.headers['Content-Type'] = 'application/octet-stream';
}
var contentType = httpRequest.headers['Content-Type'];
if (AWS.util.isBrowser()) {
if (typeof httpRequest.body === 'string' && !contentType.match(/;\s*charset=/)) {
var charset = '; charset=UTF-8';
httpRequest.headers['Content-Type'] += charset;
} else {
var replaceFn = function(_, prefix, charsetName) {
return prefix + charsetName.toUpperCase();
};
httpRequest.headers['Content-Type'] =
contentType.replace(/(;\s*charset=)(.+)$/, replaceFn);
}
}
},
/**
* @api private
*/
computableChecksumOperations: {
putBucketCors: true,
putBucketLifecycle: true,
putBucketLifecycleConfiguration: true,
putBucketTagging: true,
deleteObjects: true,
putBucketReplication: true
},
/**
* Checks whether checksums should be computed for the request.
* If the request requires checksums to be computed, this will always
* return true, otherwise it depends on whether {AWS.Config.computeChecksums}
* is set.
*
* @param req [AWS.Request] the request to check against
* @return [Boolean] whether to compute checksums for a request.
* @api private
*/
willComputeChecksums: function willComputeChecksums(req) {
if (this.computableChecksumOperations[req.operation]) return true;
if (!this.config.computeChecksums) return false;
// TODO: compute checksums for Stream objects
if (!AWS.util.Buffer.isBuffer(req.httpRequest.body) &&
typeof req.httpRequest.body !== 'string') {
return false;
}
var rules = req.service.api.operations[req.operation].input.members;
// Sha256 signing disabled, and not a presigned url
if (req.service.shouldDisableBodySigning(req) && !Object.prototype.hasOwnProperty.call(req.httpRequest.headers, 'presigned-expires')) {
if (rules.ContentMD5 && !req.params.ContentMD5) {
return true;
}
}
// V4 signer uses SHA256 signatures so only compute MD5 if it is required
if (req.service.getSignerClass(req) === AWS.Signers.V4) {
if (rules.ContentMD5 && !rules.ContentMD5.required) return false;
}
if (rules.ContentMD5 && !req.params.ContentMD5) return true;
},
/**
* A listener that computes the Content-MD5 and sets it in the header.
* @see AWS.S3.willComputeChecksums
* @api private
*/
computeContentMd5: function computeContentMd5(req) {
if (req.service.willComputeChecksums(req)) {
var md5 = AWS.util.crypto.md5(req.httpRequest.body, 'base64');
req.httpRequest.headers['Content-MD5'] = md5;
}
},
/**
* @api private
*/
computeSseCustomerKeyMd5: function computeSseCustomerKeyMd5(req) {
var keys = {
SSECustomerKey: 'x-amz-server-side-encryption-customer-key-MD5',
CopySourceSSECustomerKey: 'x-amz-copy-source-server-side-encryption-customer-key-MD5'
};
AWS.util.each(keys, function(key, header) {
if (req.params[key]) {
var value = AWS.util.crypto.md5(req.params[key], 'base64');
req.httpRequest.headers[header] = value;
}
});
},
/**
* Returns true if the bucket name should be left in the URI path for
* a request to S3. This function takes into account the current
* endpoint protocol (e.g. http or https).
*
* @api private
*/
pathStyleBucketName: function pathStyleBucketName(bucketName) {
// user can force path style requests via the configuration
if (this.config.s3ForcePathStyle) return true;
if (this.config.s3BucketEndpoint) return false;
if (this.dnsCompatibleBucketName(bucketName)) {
return (this.config.sslEnabled && bucketName.match(/\./)) ? true : false;
} else {
return true; // not dns compatible names must always use path style
}
},
/**
* Returns true if the bucket name is DNS compatible. Buckets created
* outside of the classic region MUST be DNS compatible.
*
* @api private
*/
dnsCompatibleBucketName: function dnsCompatibleBucketName(bucketName) {
var b = bucketName;
var domain = new RegExp(/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/);
var ipAddress = new RegExp(/(\d+\.){3}\d+/);
var dots = new RegExp(/\.\./);
return (b.match(domain) && !b.match(ipAddress) && !b.match(dots)) ? true : false;
},
/**
* @return [Boolean] whether response contains an error
* @api private
*/
successfulResponse: function successfulResponse(resp) {
var req = resp.request;
var httpResponse = resp.httpResponse;
if (operationsWith200StatusCodeError[req.operation] &&
httpResponse.body.toString().match('<Error>')) {
return false;
} else {
return httpResponse.statusCode < 300;
}
},
/**
* @return [Boolean] whether the error can be retried
* @api private
*/
retryableError: function retryableError(error, request) {
if (operationsWith200StatusCodeError[request.operation] &&
error.statusCode === 200) {
return true;
} else if (request._requestRegionForBucket &&
request.service.bucketRegionCache[request._requestRegionForBucket]) {
return false;
} else if (error && error.code === 'RequestTimeout') {
return true;
} else if (error &&
regionRedirectErrorCodes.indexOf(error.code) != -1 &&
error.region && error.region != request.httpRequest.region) {
request.httpRequest.region = error.region;
if (error.statusCode === 301) {
request.service.updateReqBucketRegion(request);
}
return true;
} else {
var _super = AWS.Service.prototype.retryableError;
return _super.call(this, error, request);
}
},
/**
* Updates httpRequest with region. If region is not provided, then
* the httpRequest will be updated based on httpRequest.region
*
* @api private
*/
updateReqBucketRegion: function updateReqBucketRegion(request, region) {
var httpRequest = request.httpRequest;
if (typeof region === 'string' && region.length) {
httpRequest.region = region;
}
if (!httpRequest.endpoint.host.match(/s3(?!-accelerate).*\.amazonaws\.com$/)) {
return;
}
var service = request.service;
var s3Config = service.config;
var s3BucketEndpoint = s3Config.s3BucketEndpoint;
if (s3BucketEndpoint) {
delete s3Config.s3BucketEndpoint;
}
var newConfig = AWS.util.copy(s3Config);
delete newConfig.endpoint;
newConfig.region = httpRequest.region;
httpRequest.endpoint = (new AWS.S3(newConfig)).endpoint;
service.populateURI(request);
s3Config.s3BucketEndpoint = s3BucketEndpoint;
httpRequest.headers.Host = httpRequest.endpoint.host;
if (request._asm.currentState === 'validate') {
request.removeListener('build', service.populateURI);
request.addListener('build', service.removeVirtualHostedBucketFromPath);
}
},
/**
* Provides a specialized parser for getBucketLocation -- all other
* operations are parsed by the super class.
*
* @api private
*/
extractData: function extractData(resp) {
var req = resp.request;
if (req.operation === 'getBucketLocation') {
var match = resp.httpResponse.body.toString().match(/>(.+)<\/Location/);
delete resp.data['_'];
if (match) {
resp.data.LocationConstraint = match[1];
} else {
resp.data.LocationConstraint = '';
}
}
var bucket = req.params.Bucket || null;
if (req.operation === 'deleteBucket' && typeof bucket === 'string' && !resp.error) {
req.service.clearBucketRegionCache(bucket);
} else {
var headers = resp.httpResponse.headers || {};
var region = headers['x-amz-bucket-region'] || null;
if (!region && req.operation === 'createBucket' && !resp.error) {
var createBucketConfiguration = req.params.CreateBucketConfiguration;
if (!createBucketConfiguration) {
region = 'us-east-1';
} else if (createBucketConfiguration.LocationConstraint === 'EU') {
region = 'eu-west-1';
} else {
region = createBucketConfiguration.LocationConstraint;
}
}
if (region) {
if (bucket && region !== req.service.bucketRegionCache[bucket]) {
req.service.bucketRegionCache[bucket] = region;
}
}
}
req.service.extractRequestIds(resp);
},
/**
* Extracts an error object from the http response.
*
* @api private
*/
extractError: function extractError(resp) {
var codes = {
304: 'NotModified',
403: 'Forbidden',
400: 'BadRequest',
404: 'NotFound'
};
var req = resp.request;
var code = resp.httpResponse.statusCode;
var body = resp.httpResponse.body || '';
var headers = resp.httpResponse.headers || {};
var region = headers['x-amz-bucket-region'] || null;
var bucket = req.params.Bucket || null;
var bucketRegionCache = req.service.bucketRegionCache;
if (region && bucket && region !== bucketRegionCache[bucket]) {
bucketRegionCache[bucket] = region;
}
var cachedRegion;
if (codes[code] && body.length === 0) {
if (bucket && !region) {
cachedRegion = bucketRegionCache[bucket] || null;
if (cachedRegion !== req.httpRequest.region) {
region = cachedRegion;
}
}
resp.error = AWS.util.error(new Error(), {
code: codes[code],
message: null,
region: region
});
} else {
var data = new AWS.XML.Parser().parse(body.toString());
if (data.Region && !region) {
region = data.Region;
if (bucket && region !== bucketRegionCache[bucket]) {
bucketRegionCache[bucket] = region;
}
} else if (bucket && !region && !data.Region) {
cachedRegion = bucketRegionCache[bucket] || null;
if (cachedRegion !== req.httpRequest.region) {
region = cachedRegion;
}
}
resp.error = AWS.util.error(new Error(), {
code: data.Code || code,
message: data.Message || null,
region: region
});
}
req.service.extractRequestIds(resp);
},
/**
* If region was not obtained synchronously, then send async request
* to get bucket region for errors resulting from wrong region.
*
* @api private
*/
requestBucketRegion: function requestBucketRegion(resp, done) {
var error = resp.error;
var req = resp.request;
var bucket = req.params.Bucket || null;
if (!error || !bucket || error.region || req.operation === 'listObjects' ||
(AWS.util.isNode() && req.operation === 'headBucket') ||
(error.statusCode === 400 && req.operation !== 'headObject') ||
regionRedirectErrorCodes.indexOf(error.code) === -1) {
return done();
}
var reqOperation = AWS.util.isNode() ? 'headBucket' : 'listObjects';
var reqParams = {Bucket: bucket};
if (reqOperation === 'listObjects') reqParams.MaxKeys = 0;
var regionReq = req.service[reqOperation](reqParams);
regionReq._requestRegionForBucket = bucket;
regionReq.send(function() {
var region = req.service.bucketRegionCache[bucket] || null;
error.region = region;
done();
});
},
/**
* For browser only. If NetworkingError received, will attempt to obtain
* the bucket region.
*
* @api private
*/
reqRegionForNetworkingError: function reqRegionForNetworkingError(resp, done) {
if (!AWS.util.isBrowser()) {
return done();
}
var error = resp.error;
var request = resp.request;
var bucket = request.params.Bucket;
if (!error || error.code !== 'NetworkingError' || !bucket ||
request.httpRequest.region === 'us-east-1') {
return done();
}
var service = request.service;
var bucketRegionCache = service.bucketRegionCache;
var cachedRegion = bucketRegionCache[bucket] || null;
if (cachedRegion && cachedRegion !== request.httpRequest.region) {
service.updateReqBucketRegion(request, cachedRegion);
done();
} else if (!service.dnsCompatibleBucketName(bucket)) {
service.updateReqBucketRegion(request, 'us-east-1');
if (bucketRegionCache[bucket] !== 'us-east-1') {
bucketRegionCache[bucket] = 'us-east-1';
}
done();
} else if (request.httpRequest.virtualHostedBucket) {
var getRegionReq = service.listObjects({Bucket: bucket, MaxKeys: 0});
service.updateReqBucketRegion(getRegionReq, 'us-east-1');
getRegionReq._requestRegionForBucket = bucket;
getRegionReq.send(function() {
var region = service.bucketRegionCache[bucket] || null;
if (region && region !== request.httpRequest.region) {
service.updateReqBucketRegion(request, region);
}
done();
});
} else {
// DNS-compatible path-style
// (s3ForcePathStyle or bucket name with dot over https)
// Cannot obtain region information for this case
done();
}
},
/**
* Cache for bucket region.
*
* @api private
*/
bucketRegionCache: {},
/**
* Clears bucket region cache.
*
* @api private
*/
clearBucketRegionCache: function(buckets) {
var bucketRegionCache = this.bucketRegionCache;
if (!buckets) {
buckets = Object.keys(bucketRegionCache);
} else if (typeof buckets === 'string') {
buckets = [buckets];
}
for (var i = 0; i < buckets.length; i++) {
delete bucketRegionCache[buckets[i]];
}
return bucketRegionCache;
},
/**
* Corrects request region if bucket's cached region is different
*
* @api private
*/
correctBucketRegionFromCache: function correctBucketRegionFromCache(req) {
var bucket = req.params.Bucket || null;
if (bucket) {
var service = req.service;
var requestRegion = req.httpRequest.region;
var cachedRegion = service.bucketRegionCache[bucket];
if (cachedRegion && cachedRegion !== requestRegion) {
service.updateReqBucketRegion(req, cachedRegion);
}
}
},
/**
* Extracts S3 specific request ids from the http response.
*
* @api private
*/
extractRequestIds: function extractRequestIds(resp) {
var extendedRequestId = resp.httpResponse.headers ? resp.httpResponse.headers['x-amz-id-2'] : null;
var cfId = resp.httpResponse.headers ? resp.httpResponse.headers['x-amz-cf-id'] : null;
resp.extendedRequestId = extendedRequestId;
resp.cfId = cfId;
if (resp.error) {
resp.error.requestId = resp.requestId || null;
resp.error.extendedRequestId = extendedRequestId;
resp.error.cfId = cfId;
}
},
/**
* Get a pre-signed URL for a given operation name.
*
* @note You must ensure that you have static or previously resolved
* credentials if you call this method synchronously (with no callback),
* otherwise it may not properly sign the request. If you cannot guarantee
* this (you are using an asynchronous credential provider, i.e., EC2
* IAM roles), you should always call this method with an asynchronous
* callback.
* @param operation [String] the name of the operation to call
* @param params [map] parameters to pass to the operation. See the given
* operation for the expected operation parameters. In addition, you can
* also pass the "Expires" parameter to inform S3 how long the URL should
* work for.
* @option params Expires [Integer] (900) the number of seconds to expire
* the pre-signed URL operation in. Defaults to 15 minutes.
* @param callback [Function] if a callback is provided, this function will
* pass the URL as the second parameter (after the error parameter) to
* the callback function.
* @return [String] if called synchronously (with no callback), returns the
* signed URL.
* @return [null] nothing is returned if a callback is provided.
* @example Pre-signing a getObject operation (synchronously)
* var params = {Bucket: 'bucket', Key: 'key'};
* var url = s3.getSignedUrl('getObject', params);
* console.log('The URL is', url);
* @example Pre-signing a putObject (asynchronously)
* var params = {Bucket: 'bucket', Key: 'key'};
* s3.getSignedUrl('putObject', params, function (err, url) {
* console.log('The URL is', url);
* });
* @example Pre-signing a putObject operation with a specific payload
* var params = {Bucket: 'bucket', Key: 'key', Body: 'body'};
* var url = s3.getSignedUrl('putObject', params);
* console.log('The URL is', url);
* @example Passing in a 1-minute expiry time for a pre-signed URL
* var params = {Bucket: 'bucket', Key: 'key', Expires: 60};
* var url = s3.getSignedUrl('getObject', params);
* console.log('The URL is', url); // expires in 60 seconds
*/
getSignedUrl: function getSignedUrl(operation, params, callback) {
params = AWS.util.copy(params || {});
var expires = params.Expires || 900;
delete params.Expires; // we can't validate this
var request = this.makeRequest(operation, params);
return request.presign(expires, callback);
},
/**
* @api private
*/
prepareSignedUrl: function prepareSignedUrl(request) {
request.addListener('validate', request.service.noPresignedContentLength);
request.removeListener('build', request.service.addContentType);
if (!request.params.Body) {
// no Content-MD5/SHA-256 if body is not provided
request.removeListener('build', request.service.computeContentMd5);
} else {
request.addListener('afterBuild', AWS.EventListeners.Core.COMPUTE_SHA256);
}
},
/**
* @api private
* @param request
*/
disableBodySigning: function disableBodySigning(request) {
var headers = request.httpRequest.headers;
// Add the header to anything that isn't a presigned url, unless that presigned url had a body defined
if (!Object.prototype.hasOwnProperty.call(headers, 'presigned-expires')) {
headers['X-Amz-Content-Sha256'] = 'UNSIGNED-PAYLOAD';
}
},
/**
* @api private
*/
noPresignedContentLength: function noPresignedContentLength(request) {
if (request.params.ContentLength !== undefined) {
throw AWS.util.error(new Error(), {code: 'UnexpectedParameter',
message: 'ContentLength is not supported in pre-signed URLs.'});
}
},
createBucket: function createBucket(params, callback) {
// When creating a bucket *outside* the classic region, the location
// constraint must be set for the bucket and it must match the endpoint.
// This chunk of code will set the location constraint param based
// on the region (when possible), but it will not override a passed-in
// location constraint.
if (typeof params === 'function' || !params) {
callback = callback || params;
params = {};
}
var hostname = this.endpoint.hostname;
if (hostname !== this.api.globalEndpoint && !params.CreateBucketConfiguration) {
params.CreateBucketConfiguration = { LocationConstraint: this.config.region };
}
return this.makeRequest('createBucket', params, callback);
},
/**
* @overload upload(params = {}, [options], [callback])
* Uploads an arbitrarily sized buffer, blob, or stream, using intelligent
* concurrent handling of parts if the payload is large enough. You can
* configure the concurrent queue size by setting `options`. Note that this
* is the only operation for which the SDK can retry requests with stream
* bodies.
*
* @param (see AWS.S3.putObject)
* @option (see AWS.S3.ManagedUpload.constructor)
* @return [AWS.S3.ManagedUpload] the managed upload object that can call
* `send()` or track progress.
* @example Uploading a stream object
* var params = {Bucket: 'bucket', Key: 'key', Body: stream};
* s3.upload(params, function(err, data) {
* console.log(err, data);
* });
* @example Uploading a stream with concurrency of 1 and partSize of 10mb
* var params = {Bucket: 'bucket', Key: 'key', Body: stream};
* var options = {partSize: 10 * 1024 * 1024, queueSize: 1};
* s3.upload(params, options, function(err, data) {
* console.log(err, data);
* });
* @callback callback function(err, data)
* @param err [Error] an error or null if no error occurred.
* @param data [map] The response data from the successful upload:
* * `Location` (String) the URL of the uploaded object
* * `ETag` (String) the ETag of the uploaded object
* * `Bucket` (String) the bucket to which the object was uploaded
* * `Key` (String) the key to which the object was uploaded
* @see AWS.S3.ManagedUpload
*/
upload: function upload(params, options, callback) {
if (typeof options === 'function' && callback === undefined) {
callback = options;
options = null;
}
options = options || {};
options = AWS.util.merge(options || {}, {service: this, params: params});
var uploader = new AWS.S3.ManagedUpload(options);
if (typeof callback === 'function') uploader.send(callback);
return uploader;
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | 1 1 | var AWS = require('../core');
AWS.util.update(AWS.SQS.prototype, {
/**
* @api private
*/
setupRequestListeners: function setupRequestListeners(request) {
request.addListener('build', this.buildEndpoint);
if (request.service.config.computeChecksums) {
if (request.operation === 'sendMessage') {
request.addListener('extractData', this.verifySendMessageChecksum);
} else if (request.operation === 'sendMessageBatch') {
request.addListener('extractData', this.verifySendMessageBatchChecksum);
} else if (request.operation === 'receiveMessage') {
request.addListener('extractData', this.verifyReceiveMessageChecksum);
}
}
},
/**
* @api private
*/
verifySendMessageChecksum: function verifySendMessageChecksum(response) {
if (!response.data) return;
var md5 = response.data.MD5OfMessageBody;
var body = this.params.MessageBody;
var calculatedMd5 = this.service.calculateChecksum(body);
if (calculatedMd5 !== md5) {
var msg = 'Got "' + response.data.MD5OfMessageBody +
'", expecting "' + calculatedMd5 + '".';
this.service.throwInvalidChecksumError(response,
[response.data.MessageId], msg);
}
},
/**
* @api private
*/
verifySendMessageBatchChecksum: function verifySendMessageBatchChecksum(response) {
if (!response.data) return;
var service = this.service;
var entries = {};
var errors = [];
var messageIds = [];
AWS.util.arrayEach(response.data.Successful, function (entry) {
entries[entry.Id] = entry;
});
AWS.util.arrayEach(this.params.Entries, function (entry) {
if (entries[entry.Id]) {
var md5 = entries[entry.Id].MD5OfMessageBody;
var body = entry.MessageBody;
if (!service.isChecksumValid(md5, body)) {
errors.push(entry.Id);
messageIds.push(entries[entry.Id].MessageId);
}
}
});
if (errors.length > 0) {
service.throwInvalidChecksumError(response, messageIds,
'Invalid messages: ' + errors.join(', '));
}
},
/**
* @api private
*/
verifyReceiveMessageChecksum: function verifyReceiveMessageChecksum(response) {
if (!response.data) return;
var service = this.service;
var messageIds = [];
AWS.util.arrayEach(response.data.Messages, function(message) {
var md5 = message.MD5OfBody;
var body = message.Body;
if (!service.isChecksumValid(md5, body)) {
messageIds.push(message.MessageId);
}
});
if (messageIds.length > 0) {
service.throwInvalidChecksumError(response, messageIds,
'Invalid messages: ' + messageIds.join(', '));
}
},
/**
* @api private
*/
throwInvalidChecksumError: function throwInvalidChecksumError(response, ids, message) {
response.error = AWS.util.error(new Error(), {
retryable: true,
code: 'InvalidChecksum',
messageIds: ids,
message: response.request.operation +
' returned an invalid MD5 response. ' + message
});
},
/**
* @api private
*/
isChecksumValid: function isChecksumValid(checksum, data) {
return this.calculateChecksum(data) === checksum;
},
/**
* @api private
*/
calculateChecksum: function calculateChecksum(data) {
return AWS.util.crypto.md5(data, 'hex');
},
/**
* @api private
*/
buildEndpoint: function buildEndpoint(request) {
var url = request.httpRequest.params.QueueUrl;
if (url) {
request.httpRequest.endpoint = new AWS.Endpoint(url);
// signature version 4 requires the region name to be set,
// sqs queue urls contain the region name
var matches = request.httpRequest.endpoint.host.match(/^sqs\.(.+?)\./);
if (matches) request.httpRequest.region = matches[1];
}
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | 1 1 | var AWS = require('../core');
AWS.util.update(AWS.STS.prototype, {
/**
* @overload credentialsFrom(data, credentials = null)
* Creates a credentials object from STS response data containing
* credentials information. Useful for quickly setting AWS credentials.
*
* @note This is a low-level utility function. If you want to load temporary
* credentials into your process for subsequent requests to AWS resources,
* you should use {AWS.TemporaryCredentials} instead.
* @param data [map] data retrieved from a call to {getFederatedToken},
* {getSessionToken}, {assumeRole}, or {assumeRoleWithWebIdentity}.
* @param credentials [AWS.Credentials] an optional credentials object to
* fill instead of creating a new object. Useful when modifying an
* existing credentials object from a refresh call.
* @return [AWS.TemporaryCredentials] the set of temporary credentials
* loaded from a raw STS operation response.
* @example Using credentialsFrom to load global AWS credentials
* var sts = new AWS.STS();
* sts.getSessionToken(function (err, data) {
* if (err) console.log("Error getting credentials");
* else {
* AWS.config.credentials = sts.credentialsFrom(data);
* }
* });
* @see AWS.TemporaryCredentials
*/
credentialsFrom: function credentialsFrom(data, credentials) {
if (!data) return null;
if (!credentials) credentials = new AWS.TemporaryCredentials();
credentials.expired = false;
credentials.accessKeyId = data.Credentials.AccessKeyId;
credentials.secretAccessKey = data.Credentials.SecretAccessKey;
credentials.sessionToken = data.Credentials.SessionToken;
credentials.expireTime = data.Credentials.Expiration;
return credentials;
},
assumeRoleWithWebIdentity: function assumeRoleWithWebIdentity(params, callback) {
return this.makeUnauthenticatedRequest('assumeRoleWithWebIdentity', params, callback);
},
assumeRoleWithSAML: function assumeRoleWithSAML(params, callback) {
return this.makeUnauthenticatedRequest('assumeRoleWithSAML', params, callback);
}
});
|
| 1 2 3 4 5 6 7 8 9 10 11 12 | 1 1 1 | var AWS = require('../core');
AWS.util.hideProperties(AWS, ['SimpleWorkflow']);
/**
* @constant
* @readonly
* Backwards compatibility for access to the {AWS.SWF} service class.
*/
AWS.SimpleWorkflow = AWS.SWF;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| presign.js | 11.29% | (7 / 62) | 0% | (0 / 24) | 0% | (0 / 5) | 11.86% | (7 / 59) | |
| request_signer.js | 50% | (10 / 20) | 0% | (0 / 5) | 0% | (0 / 4) | 50% | (10 / 20) | |
| s3.js | 6.35% | (4 / 63) | 0% | (0 / 34) | 0% | (0 / 11) | 6.56% | (4 / 61) | |
| v2.js | 16.67% | (4 / 24) | 0% | (0 / 4) | 0% | (0 / 3) | 17.39% | (4 / 23) | |
| v3.js | 12.5% | (4 / 32) | 0% | (0 / 7) | 0% | (0 / 10) | 12.5% | (4 / 32) | |
| v3https.js | 71.43% | (5 / 7) | 100% | (0 / 0) | 0% | (0 / 2) | 71.43% | (5 / 7) | |
| v4.js | 6.9% | (8 / 116) | 0% | (0 / 59) | 0% | (0 / 21) | 7.14% | (8 / 112) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | 1 1 1 1 1 1 1 | var AWS = require('../core');
var inherit = AWS.util.inherit;
/**
* @api private
*/
var expiresHeader = 'presigned-expires';
/**
* @api private
*/
function signedUrlBuilder(request) {
var expires = request.httpRequest.headers[expiresHeader];
var signerClass = request.service.getSignerClass(request);
delete request.httpRequest.headers['User-Agent'];
delete request.httpRequest.headers['X-Amz-User-Agent'];
if (signerClass === AWS.Signers.V4) {
if (expires > 604800) { // one week expiry is invalid
var message = 'Presigning does not support expiry time greater ' +
'than a week with SigV4 signing.';
throw AWS.util.error(new Error(), {
code: 'InvalidExpiryTime', message: message, retryable: false
});
}
request.httpRequest.headers[expiresHeader] = expires;
} else if (signerClass === AWS.Signers.S3) {
request.httpRequest.headers[expiresHeader] = parseInt(
AWS.util.date.unixTimestamp() + expires, 10).toString();
} else {
throw AWS.util.error(new Error(), {
message: 'Presigning only supports S3 or SigV4 signing.',
code: 'UnsupportedSigner', retryable: false
});
}
}
/**
* @api private
*/
function signedUrlSigner(request) {
var endpoint = request.httpRequest.endpoint;
var parsedUrl = AWS.util.urlParse(request.httpRequest.path);
var queryParams = {};
if (parsedUrl.search) {
queryParams = AWS.util.queryStringParse(parsedUrl.search.substr(1));
}
AWS.util.each(request.httpRequest.headers, function (key, value) {
if (key === expiresHeader) key = 'Expires';
if (key.indexOf('x-amz-meta-') === 0) {
// Delete existing, potentially not normalized key
delete queryParams[key];
key = key.toLowerCase();
}
queryParams[key] = value;
});
delete request.httpRequest.headers[expiresHeader];
var auth = queryParams['Authorization'].split(' ');
if (auth[0] === 'AWS') {
auth = auth[1].split(':');
queryParams['AWSAccessKeyId'] = auth[0];
queryParams['Signature'] = auth[1];
} else if (auth[0] === 'AWS4-HMAC-SHA256') { // SigV4 signing
auth.shift();
var rest = auth.join(' ');
var signature = rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];
queryParams['X-Amz-Signature'] = signature;
delete queryParams['Expires'];
}
delete queryParams['Authorization'];
delete queryParams['Host'];
// build URL
endpoint.pathname = parsedUrl.pathname;
endpoint.search = AWS.util.queryParamsToString(queryParams);
}
/**
* @api private
*/
AWS.Signers.Presign = inherit({
/**
* @api private
*/
sign: function sign(request, expireTime, callback) {
request.httpRequest.headers[expiresHeader] = expireTime || 3600;
request.on('build', signedUrlBuilder);
request.on('sign', signedUrlSigner);
request.removeListener('afterBuild',
AWS.EventListeners.Core.SET_CONTENT_LENGTH);
request.removeListener('afterBuild',
AWS.EventListeners.Core.COMPUTE_SHA256);
request.emit('beforePresign', [request]);
if (callback) {
request.build(function() {
if (this.response.error) callback(this.response.error);
else {
callback(null, AWS.util.urlFormat(request.httpRequest.endpoint));
}
});
} else {
request.build();
if (request.response.error) throw request.response.error;
return AWS.util.urlFormat(request.httpRequest.endpoint);
}
}
});
module.exports = AWS.Signers.Presign;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 1 1 1 1 1 1 1 1 1 1 | var AWS = require('../core');
var inherit = AWS.util.inherit;
/**
* @api private
*/
AWS.Signers.RequestSigner = inherit({
constructor: function RequestSigner(request) {
this.request = request;
},
setServiceClientId: function setServiceClientId(id) {
this.serviceClientId = id;
},
getServiceClientId: function getServiceClientId() {
return this.serviceClientId;
}
});
AWS.Signers.RequestSigner.getVersion = function getVersion(version) {
switch (version) {
case 'v2': return AWS.Signers.V2;
case 'v3': return AWS.Signers.V3;
case 'v4': return AWS.Signers.V4;
case 's3': return AWS.Signers.S3;
case 'v3https': return AWS.Signers.V3Https;
}
throw new Error('Unknown signing version ' + version);
};
require('./v2');
require('./v3');
require('./v3https');
require('./v4');
require('./s3');
require('./presign');
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | 1 1 1 1 | var AWS = require('../core');
var inherit = AWS.util.inherit;
/**
* @api private
*/
AWS.Signers.S3 = inherit(AWS.Signers.RequestSigner, {
/**
* When building the stringToSign, these sub resource params should be
* part of the canonical resource string with their NON-decoded values
*/
subResources: {
'acl': 1,
'accelerate': 1,
'cors': 1,
'lifecycle': 1,
'delete': 1,
'location': 1,
'logging': 1,
'notification': 1,
'partNumber': 1,
'policy': 1,
'requestPayment': 1,
'replication': 1,
'restore': 1,
'tagging': 1,
'torrent': 1,
'uploadId': 1,
'uploads': 1,
'versionId': 1,
'versioning': 1,
'versions': 1,
'website': 1
},
// when building the stringToSign, these querystring params should be
// part of the canonical resource string with their NON-encoded values
responseHeaders: {
'response-content-type': 1,
'response-content-language': 1,
'response-expires': 1,
'response-cache-control': 1,
'response-content-disposition': 1,
'response-content-encoding': 1
},
addAuthorization: function addAuthorization(credentials, date) {
if (!this.request.headers['presigned-expires']) {
this.request.headers['X-Amz-Date'] = AWS.util.date.rfc822(date);
}
if (credentials.sessionToken) {
// presigned URLs require this header to be lowercased
this.request.headers['x-amz-security-token'] = credentials.sessionToken;
}
var signature = this.sign(credentials.secretAccessKey, this.stringToSign());
var auth = 'AWS ' + credentials.accessKeyId + ':' + signature;
this.request.headers['Authorization'] = auth;
},
stringToSign: function stringToSign() {
var r = this.request;
var parts = [];
parts.push(r.method);
parts.push(r.headers['Content-MD5'] || '');
parts.push(r.headers['Content-Type'] || '');
// This is the "Date" header, but we use X-Amz-Date.
// The S3 signing mechanism requires us to pass an empty
// string for this Date header regardless.
parts.push(r.headers['presigned-expires'] || '');
var headers = this.canonicalizedAmzHeaders();
if (headers) parts.push(headers);
parts.push(this.canonicalizedResource());
return parts.join('\n');
},
canonicalizedAmzHeaders: function canonicalizedAmzHeaders() {
var amzHeaders = [];
AWS.util.each(this.request.headers, function (name) {
if (name.match(/^x-amz-/i))
amzHeaders.push(name);
});
amzHeaders.sort(function (a, b) {
return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
});
var parts = [];
AWS.util.arrayEach.call(this, amzHeaders, function (name) {
parts.push(name.toLowerCase() + ':' + String(this.request.headers[name]));
});
return parts.join('\n');
},
canonicalizedResource: function canonicalizedResource() {
var r = this.request;
var parts = r.path.split('?');
var path = parts[0];
var querystring = parts[1];
var resource = '';
if (r.virtualHostedBucket)
resource += '/' + r.virtualHostedBucket;
resource += path;
if (querystring) {
// collect a list of sub resources and query params that need to be signed
var resources = [];
AWS.util.arrayEach.call(this, querystring.split('&'), function (param) {
var name = param.split('=')[0];
var value = param.split('=')[1];
if (this.subResources[name] || this.responseHeaders[name]) {
var subresource = { name: name };
if (value !== undefined) {
if (this.subResources[name]) {
subresource.value = value;
} else {
subresource.value = decodeURIComponent(value);
}
}
resources.push(subresource);
}
});
resources.sort(function (a, b) { return a.name < b.name ? -1 : 1; });
if (resources.length) {
querystring = [];
AWS.util.arrayEach(resources, function (res) {
if (res.value === undefined) {
querystring.push(res.name);
} else {
querystring.push(res.name + '=' + res.value);
}
});
resource += '?' + querystring.join('&');
}
}
return resource;
},
sign: function sign(secret, string) {
return AWS.util.crypto.hmac(secret, string, 'base64', 'sha1');
}
});
module.exports = AWS.Signers.S3;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 1 1 1 1 | var AWS = require('../core');
var inherit = AWS.util.inherit;
/**
* @api private
*/
AWS.Signers.V2 = inherit(AWS.Signers.RequestSigner, {
addAuthorization: function addAuthorization(credentials, date) {
if (!date) date = AWS.util.date.getDate();
var r = this.request;
r.params.Timestamp = AWS.util.date.iso8601(date);
r.params.SignatureVersion = '2';
r.params.SignatureMethod = 'HmacSHA256';
r.params.AWSAccessKeyId = credentials.accessKeyId;
if (credentials.sessionToken) {
r.params.SecurityToken = credentials.sessionToken;
}
delete r.params.Signature; // delete old Signature for re-signing
r.params.Signature = this.signature(credentials);
r.body = AWS.util.queryParamsToString(r.params);
r.headers['Content-Length'] = r.body.length;
},
signature: function signature(credentials) {
return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
},
stringToSign: function stringToSign() {
var parts = [];
parts.push(this.request.method);
parts.push(this.request.endpoint.host.toLowerCase());
parts.push(this.request.pathname());
parts.push(AWS.util.queryParamsToString(this.request.params));
return parts.join('\n');
}
});
module.exports = AWS.Signers.V2;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | 1 1 1 1 | var AWS = require('../core');
var inherit = AWS.util.inherit;
/**
* @api private
*/
AWS.Signers.V3 = inherit(AWS.Signers.RequestSigner, {
addAuthorization: function addAuthorization(credentials, date) {
var datetime = AWS.util.date.rfc822(date);
this.request.headers['X-Amz-Date'] = datetime;
if (credentials.sessionToken) {
this.request.headers['x-amz-security-token'] = credentials.sessionToken;
}
this.request.headers['X-Amzn-Authorization'] =
this.authorization(credentials, datetime);
},
authorization: function authorization(credentials) {
return 'AWS3 ' +
'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
'Algorithm=HmacSHA256,' +
'SignedHeaders=' + this.signedHeaders() + ',' +
'Signature=' + this.signature(credentials);
},
signedHeaders: function signedHeaders() {
var headers = [];
AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
headers.push(h.toLowerCase());
});
return headers.sort().join(';');
},
canonicalHeaders: function canonicalHeaders() {
var headers = this.request.headers;
var parts = [];
AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
parts.push(h.toLowerCase().trim() + ':' + String(headers[h]).trim());
});
return parts.sort().join('\n') + '\n';
},
headersToSign: function headersToSign() {
var headers = [];
AWS.util.each(this.request.headers, function iterator(k) {
if (k === 'Host' || k === 'Content-Encoding' || k.match(/^X-Amz/i)) {
headers.push(k);
}
});
return headers;
},
signature: function signature(credentials) {
return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
},
stringToSign: function stringToSign() {
var parts = [];
parts.push(this.request.method);
parts.push('/');
parts.push('');
parts.push(this.canonicalHeaders());
parts.push(this.request.body);
return AWS.util.crypto.sha256(parts.join('\n'));
}
});
module.exports = AWS.Signers.V3;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 1 1 1 1 1 | var AWS = require('../core');
var inherit = AWS.util.inherit;
require('./v3');
/**
* @api private
*/
AWS.Signers.V3Https = inherit(AWS.Signers.V3, {
authorization: function authorization(credentials) {
return 'AWS3-HTTPS ' +
'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
'Algorithm=HmacSHA256,' +
'Signature=' + this.signature(credentials);
},
stringToSign: function stringToSign() {
return this.request.headers['X-Amz-Date'];
}
});
module.exports = AWS.Signers.V3Https;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | 1 1 1 1 1 1 1 1 | var AWS = require('../core');
var inherit = AWS.util.inherit;
/**
* @api private
*/
var cachedSecret = {};
/**
* @api private
*/
var cacheQueue = [];
/**
* @api private
*/
var maxCacheEntries = 50;
/**
* @api private
*/
var expiresHeader = 'presigned-expires';
/**
* @api private
*/
AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, {
constructor: function V4(request, serviceName, signatureCache) {
AWS.Signers.RequestSigner.call(this, request);
this.serviceName = serviceName;
this.signatureCache = signatureCache;
},
algorithm: 'AWS4-HMAC-SHA256',
addAuthorization: function addAuthorization(credentials, date) {
var datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, '');
if (this.isPresigned()) {
this.updateForPresigned(credentials, datetime);
} else {
this.addHeaders(credentials, datetime);
}
this.request.headers['Authorization'] =
this.authorization(credentials, datetime);
},
addHeaders: function addHeaders(credentials, datetime) {
this.request.headers['X-Amz-Date'] = datetime;
if (credentials.sessionToken) {
this.request.headers['x-amz-security-token'] = credentials.sessionToken;
}
},
updateForPresigned: function updateForPresigned(credentials, datetime) {
var credString = this.credentialString(datetime);
var qs = {
'X-Amz-Date': datetime,
'X-Amz-Algorithm': this.algorithm,
'X-Amz-Credential': credentials.accessKeyId + '/' + credString,
'X-Amz-Expires': this.request.headers[expiresHeader],
'X-Amz-SignedHeaders': this.signedHeaders()
};
if (credentials.sessionToken) {
qs['X-Amz-Security-Token'] = credentials.sessionToken;
}
if (this.request.headers['Content-Type']) {
qs['Content-Type'] = this.request.headers['Content-Type'];
}
if (this.request.headers['Content-MD5']) {
qs['Content-MD5'] = this.request.headers['Content-MD5'];
}
if (this.request.headers['Cache-Control']) {
qs['Cache-Control'] = this.request.headers['Cache-Control'];
}
// need to pull in any other X-Amz-* headers
AWS.util.each.call(this, this.request.headers, function(key, value) {
if (key === expiresHeader) return;
if (this.isSignableHeader(key)) {
var lowerKey = key.toLowerCase();
// Metadata should be normalized
if (lowerKey.indexOf('x-amz-meta-') === 0) {
qs[lowerKey] = value;
} else if (lowerKey.indexOf('x-amz-') === 0) {
qs[key] = value;
}
}
});
var sep = this.request.path.indexOf('?') >= 0 ? '&' : '?';
this.request.path += sep + AWS.util.queryParamsToString(qs);
},
authorization: function authorization(credentials, datetime) {
var parts = [];
var credString = this.credentialString(datetime);
parts.push(this.algorithm + ' Credential=' +
credentials.accessKeyId + '/' + credString);
parts.push('SignedHeaders=' + this.signedHeaders());
parts.push('Signature=' + this.signature(credentials, datetime));
return parts.join(', ');
},
signature: function signature(credentials, datetime) {
var cache = null;
var cacheIdentifier = this.serviceName + (this.getServiceClientId() ? '_' + this.getServiceClientId() : '');
if (this.signatureCache) {
var cache = cachedSecret[cacheIdentifier];
// If there isn't already a cache entry, we'll be adding one
if (!cache) {
cacheQueue.push(cacheIdentifier);
if (cacheQueue.length > maxCacheEntries) {
// remove the oldest entry (may not be last one used)
delete cachedSecret[cacheQueue.shift()];
}
}
}
var date = datetime.substr(0, 8);
if (!cache ||
cache.akid !== credentials.accessKeyId ||
cache.region !== this.request.region ||
cache.date !== date) {
var kSecret = credentials.secretAccessKey;
var kDate = AWS.util.crypto.hmac('AWS4' + kSecret, date, 'buffer');
var kRegion = AWS.util.crypto.hmac(kDate, this.request.region, 'buffer');
var kService = AWS.util.crypto.hmac(kRegion, this.serviceName, 'buffer');
var kCredentials = AWS.util.crypto.hmac(kService, 'aws4_request', 'buffer');
if (!this.signatureCache) {
return AWS.util.crypto.hmac(kCredentials, this.stringToSign(datetime), 'hex');
}
cachedSecret[cacheIdentifier] = {
region: this.request.region, date: date,
key: kCredentials, akid: credentials.accessKeyId
};
}
var key = cachedSecret[cacheIdentifier].key;
return AWS.util.crypto.hmac(key, this.stringToSign(datetime), 'hex');
},
stringToSign: function stringToSign(datetime) {
var parts = [];
parts.push('AWS4-HMAC-SHA256');
parts.push(datetime);
parts.push(this.credentialString(datetime));
parts.push(this.hexEncodedHash(this.canonicalString()));
return parts.join('\n');
},
canonicalString: function canonicalString() {
var parts = [], pathname = this.request.pathname();
if (this.serviceName !== 's3') pathname = AWS.util.uriEscapePath(pathname);
parts.push(this.request.method);
parts.push(pathname);
parts.push(this.request.search());
parts.push(this.canonicalHeaders() + '\n');
parts.push(this.signedHeaders());
parts.push(this.hexEncodedBodyHash());
return parts.join('\n');
},
canonicalHeaders: function canonicalHeaders() {
var headers = [];
AWS.util.each.call(this, this.request.headers, function (key, item) {
headers.push([key, item]);
});
headers.sort(function (a, b) {
return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1;
});
var parts = [];
AWS.util.arrayEach.call(this, headers, function (item) {
var key = item[0].toLowerCase();
if (this.isSignableHeader(key)) {
parts.push(key + ':' +
this.canonicalHeaderValues(item[1].toString()));
}
});
return parts.join('\n');
},
canonicalHeaderValues: function canonicalHeaderValues(values) {
return values.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');
},
signedHeaders: function signedHeaders() {
var keys = [];
AWS.util.each.call(this, this.request.headers, function (key) {
key = key.toLowerCase();
if (this.isSignableHeader(key)) keys.push(key);
});
return keys.sort().join(';');
},
credentialString: function credentialString(datetime) {
var parts = [];
parts.push(datetime.substr(0, 8));
parts.push(this.request.region);
parts.push(this.serviceName);
parts.push('aws4_request');
return parts.join('/');
},
hexEncodedHash: function hash(string) {
return AWS.util.crypto.sha256(string, 'hex');
},
hexEncodedBodyHash: function hexEncodedBodyHash() {
if (this.isPresigned() && this.serviceName === 's3' && !this.request.body) {
return 'UNSIGNED-PAYLOAD';
} else if (this.request.headers['X-Amz-Content-Sha256']) {
return this.request.headers['X-Amz-Content-Sha256'];
} else {
return this.hexEncodedHash(this.request.body || '');
}
},
unsignableHeaders: ['authorization', 'content-type', 'content-length',
'user-agent', expiresHeader, 'expect'],
isSignableHeader: function isSignableHeader(key) {
if (key.toLowerCase().indexOf('x-amz-') === 0) return true;
return this.unsignableHeaders.indexOf(key) < 0;
},
isPresigned: function isPresigned() {
return this.request.headers[expiresHeader] ? true : false;
}
});
module.exports = AWS.Signers.V4;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| builder.js | 18.64% | (11 / 59) | 0% | (0 / 40) | 0% | (0 / 12) | 19.64% | (11 / 56) | |
| node_parser.js | 13.54% | (13 / 96) | 0% | (0 / 74) | 0% | (0 / 13) | 14.61% | (13 / 89) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | 1 1 1 1 1 1 1 1 1 1 1 | var util = require('../util');
var builder = require('xmlbuilder');
function XmlBuilder() { }
XmlBuilder.prototype.toXML = function(params, shape, rootElement, noEmpty) {
var xml = builder.create(rootElement);
applyNamespaces(xml, shape);
serialize(xml, params, shape);
return xml.children.length > 0 || noEmpty ? xml.root().toString() : '';
};
function serialize(xml, value, shape) {
switch (shape.type) {
case 'structure': return serializeStructure(xml, value, shape);
case 'map': return serializeMap(xml, value, shape);
case 'list': return serializeList(xml, value, shape);
default: return serializeScalar(xml, value, shape);
}
}
function serializeStructure(xml, params, shape) {
util.arrayEach(shape.memberNames, function(memberName) {
var memberShape = shape.members[memberName];
if (memberShape.location !== 'body') return;
var value = params[memberName];
var name = memberShape.name;
if (value !== undefined && value !== null) {
if (memberShape.isXmlAttribute) {
xml.att(name, value);
} else if (memberShape.flattened) {
serialize(xml, value, memberShape);
} else {
var element = xml.ele(name);
applyNamespaces(element, memberShape);
serialize(element, value, memberShape);
}
}
});
}
function serializeMap(xml, map, shape) {
var xmlKey = shape.key.name || 'key';
var xmlValue = shape.value.name || 'value';
util.each(map, function(key, value) {
var entry = xml.ele(shape.flattened ? shape.name : 'entry');
serialize(entry.ele(xmlKey), key, shape.key);
serialize(entry.ele(xmlValue), value, shape.value);
});
}
function serializeList(xml, list, shape) {
if (shape.flattened) {
util.arrayEach(list, function(value) {
var name = shape.member.name || shape.name;
var element = xml.ele(name);
serialize(element, value, shape.member);
});
} else {
util.arrayEach(list, function(value) {
var name = shape.member.name || 'member';
var element = xml.ele(name);
serialize(element, value, shape.member);
});
}
}
function serializeScalar(xml, value, shape) {
xml.txt(shape.toWireFormat(value));
}
function applyNamespaces(xml, shape) {
var uri, prefix = 'xmlns';
if (shape.xmlNamespaceUri) {
uri = shape.xmlNamespaceUri;
if (shape.xmlNamespacePrefix) prefix += ':' + shape.xmlNamespacePrefix;
} else if (xml.isRoot && shape.api.xmlNamespaceUri) {
uri = shape.api.xmlNamespaceUri;
}
if (uri) xml.att(prefix, uri);
}
module.exports = XmlBuilder;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | 1 1 1 1 1 1 1 1 1 1 1 1 1 | var util = require('../util');
var Shape = require('../model/shape');
var xml2js = require('xml2js');
/**
* @api private
*/
var options = { // options passed to xml2js parser
explicitCharkey: false, // undocumented
trim: false, // trim the leading/trailing whitespace from text nodes
normalize: false, // trim interior whitespace inside text nodes
explicitRoot: false, // return the root node in the resulting object?
emptyTag: null, // the default value for empty nodes
explicitArray: true, // always put child nodes in an array
ignoreAttrs: false, // ignore attributes, only create text nodes
mergeAttrs: false, // merge attributes and child elements
validator: null // a callable validator
};
function NodeXmlParser() { }
NodeXmlParser.prototype.parse = function(xml, shape) {
shape = shape || {};
var result = null;
var error = null;
var parser = new xml2js.Parser(options);
parser.parseString(xml, function (e, r) {
error = e;
result = r;
});
if (result) {
var data = parseXml(result, shape);
if (result.ResponseMetadata) {
data.ResponseMetadata = parseXml(result.ResponseMetadata[0], {});
}
return data;
} else if (error) {
throw util.error(error, {code: 'XMLParserError', retryable: true});
} else { // empty xml document
return parseXml({}, shape);
}
};
function parseXml(xml, shape) {
switch (shape.type) {
case 'structure': return parseStructure(xml, shape);
case 'map': return parseMap(xml, shape);
case 'list': return parseList(xml, shape);
case undefined: case null: return parseUnknown(xml);
default: return parseScalar(xml, shape);
}
}
function parseStructure(xml, shape) {
var data = {};
if (xml === null) return data;
util.each(shape.members, function(memberName, memberShape) {
var xmlName = memberShape.name;
if (Object.prototype.hasOwnProperty.call(xml, xmlName) && Array.isArray(xml[xmlName])) {
var xmlChild = xml[xmlName];
if (!memberShape.flattened) xmlChild = xmlChild[0];
data[memberName] = parseXml(xmlChild, memberShape);
} else if (memberShape.isXmlAttribute &&
xml.$ && Object.prototype.hasOwnProperty.call(xml.$, xmlName)) {
data[memberName] = parseScalar(xml.$[xmlName], memberShape);
} else if (memberShape.type === 'list') {
data[memberName] = memberShape.defaultValue;
}
});
return data;
}
function parseMap(xml, shape) {
var data = {};
if (xml === null) return data;
var xmlKey = shape.key.name || 'key';
var xmlValue = shape.value.name || 'value';
var iterable = shape.flattened ? xml : xml.entry;
if (Array.isArray(iterable)) {
util.arrayEach(iterable, function(child) {
data[child[xmlKey][0]] = parseXml(child[xmlValue][0], shape.value);
});
}
return data;
}
function parseList(xml, shape) {
var data = [];
var name = shape.member.name || 'member';
if (shape.flattened) {
util.arrayEach(xml, function(xmlChild) {
data.push(parseXml(xmlChild, shape.member));
});
} else if (xml && Array.isArray(xml[name])) {
util.arrayEach(xml[name], function(child) {
data.push(parseXml(child, shape.member));
});
}
return data;
}
function parseScalar(text, shape) {
if (text && text.$ && text.$.encoding === 'base64') {
shape = new Shape.create({type: text.$.encoding});
}
if (text && text._) text = text._;
if (typeof shape.toType === 'function') {
return shape.toType(text);
} else {
return text;
}
}
function parseUnknown(xml) {
if (xml === undefined || xml === null) return '';
if (typeof xml === 'string') return xml;
// parse a list
if (Array.isArray(xml)) {
var arr = [];
for (i = 0; i < xml.length; i++) {
arr.push(parseXml(xml[i], {}));
}
return arr;
}
// empty object
var keys = Object.keys(xml), i;
if (keys.length === 0 || keys === ['$']) {
return {};
}
// object, parse as structure
var data = {};
for (i = 0; i < keys.length; i++) {
var key = keys[i], value = xml[key];
if (key === '$') continue;
if (value.length > 1) { // this member is a list
data[key] = parseList(value, {member: {}});
} else { // this member is a single item
data[key] = parseXml(value[0], {});
}
}
return data;
}
module.exports = NodeXmlParser;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| any.js | 38.46% | (5 / 13) | 100% | (0 / 0) | 25% | (1 / 4) | 38.46% | (5 / 13) | |
| async.js | 36.89% | (38 / 103) | 4.17% | (1 / 24) | 3.7% | (1 / 27) | 36% | (36 / 100) | |
| bind.js | 25.64% | (10 / 39) | 0% | (0 / 10) | 11.11% | (1 / 9) | 26.32% | (10 / 38) | |
| bluebird.js | 63.64% | (7 / 11) | 25% | (1 / 4) | 0% | (0 / 1) | 75% | (6 / 8) | |
| call_get.js | 30.67% | (23 / 75) | 7.14% | (2 / 28) | 8.33% | (1 / 12) | 33.33% | (23 / 69) | |
| cancel.js | 23.38% | (18 / 77) | 0% | (0 / 40) | 7.14% | (1 / 14) | 24.66% | (18 / 73) | |
| catch_filter.js | 24.14% | (7 / 29) | 0% | (0 / 17) | 33.33% | (1 / 3) | 25% | (7 / 28) | |
| context.js | 31.48% | (17 / 54) | 0% | (0 / 12) | 14.29% | (2 / 14) | 33.33% | (17 / 51) | |
| debuggability.js | 25.63% | (133 / 519) | 12.33% | (37 / 300) | 8.89% | (8 / 90) | 26.51% | (132 / 498) | |
| direct_resolve.js | 24.14% | (7 / 29) | 0% | (0 / 10) | 11.11% | (1 / 9) | 29.17% | (7 / 24) | |
| each.js | 64.29% | (9 / 14) | 100% | (0 / 0) | 16.67% | (1 / 6) | 64.29% | (9 / 14) | |
| errors.js | 49.23% | (32 / 65) | 11.11% | (2 / 18) | 25% | (1 / 4) | 50% | (32 / 64) | |
| es5.js | 12.5% | (4 / 32) | 14.29% | (1 / 7) | 11.11% | (1 / 9) | 12.5% | (4 / 32) | |
| filter.js | 66.67% | (4 / 6) | 100% | (0 / 0) | 33.33% | (1 / 3) | 66.67% | (4 / 6) | |
| finally.js | 24.62% | (16 / 65) | 0% | (0 / 24) | 8.33% | (1 / 12) | 25.4% | (16 / 63) | |
| generators.js | 15.49% | (22 / 142) | 0% | (0 / 42) | 5.88% | (1 / 17) | 15.71% | (22 / 140) | |
| join.js | 46.48% | (33 / 71) | 7.14% | (2 / 28) | 71.43% | (5 / 7) | 49.25% | (33 / 67) | |
| map.js | 14.81% | (16 / 108) | 0% | (0 / 57) | 10% | (1 / 10) | 15.53% | (16 / 103) | |
| method.js | 16.67% | (6 / 36) | 0% | (0 / 10) | 20% | (1 / 5) | 16.67% | (6 / 36) | |
| nodeback.js | 25% | (10 / 40) | 0% | (0 / 12) | 0% | (0 / 4) | 27.78% | (10 / 36) | |
| nodeify.js | 26.47% | (9 / 34) | 0% | (0 / 18) | 20% | (1 / 5) | 27.27% | (9 / 33) | |
| promise.js | 29.68% | (149 / 502) | 1% | (2 / 201) | 4.17% | (3 / 72) | 30.85% | (149 / 483) | |
| promise_array.js | 18.1% | (21 / 116) | 0% | (0 / 48) | 5.88% | (1 / 17) | 18.58% | (21 / 113) | |
| promisify.js | 22.15% | (35 / 158) | 2.9% | (2 / 69) | 4.35% | (1 / 23) | 23.03% | (35 / 152) | |
| props.js | 27.85% | (22 / 79) | 6.25% | (1 / 16) | 15.38% | (2 / 13) | 26.92% | (21 / 78) | |
| queue.js | 24.59% | (15 / 61) | 0% | (0 / 4) | 9.09% | (1 / 11) | 24.59% | (15 / 61) | |
| race.js | 22.22% | (6 / 27) | 0% | (0 / 10) | 16.67% | (1 / 6) | 22.22% | (6 / 27) | |
| reduce.js | 21.28% | (20 / 94) | 0% | (0 / 38) | 6.25% | (1 / 16) | 21.74% | (20 / 92) | |
| schedule.js | 20.45% | (9 / 44) | 19.05% | (4 / 21) | 0% | (0 / 11) | 20.93% | (9 / 43) | |
| settle.js | 35.71% | (10 / 28) | 0% | (0 / 2) | 14.29% | (1 / 7) | 35.71% | (10 / 28) | |
| some.js | 32.18% | (28 / 87) | 0% | (0 / 29) | 4.76% | (1 / 21) | 32.18% | (28 / 87) | |
| synchronous_inspection.js | 40% | (20 / 50) | 0% | (0 / 8) | 5.26% | (1 / 19) | 40% | (20 / 50) | |
| thenables.js | 21.31% | (13 / 61) | 0% | (0 / 26) | 12.5% | (1 / 8) | 24.07% | (13 / 54) | |
| timers.js | 21.82% | (12 / 55) | 0% | (0 / 18) | 8.33% | (1 / 12) | 22.64% | (12 / 53) | |
| using.js | 20.28% | (29 / 143) | 0% | (0 / 49) | 4% | (1 / 25) | 21.01% | (29 / 138) | |
| util.js | 41.21% | (82 / 199) | 25.42% | (30 / 118) | 34.21% | (13 / 38) | 41.94% | (78 / 186) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 1 1 1 1 1 | "use strict";
module.exports = function(Promise) {
var SomePromiseArray = Promise._SomePromiseArray;
function any(promises) {
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(1);
ret.setUnwrap();
ret.init();
return promise;
}
Promise.any = function (promises) {
return any(promises);
};
Promise.prototype.any = function () {
return any(this);
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
var firstLineError;
try {throw new Error(); } catch (e) {firstLineError = e;}
var schedule = require("./schedule");
var Queue = require("./queue");
var util = require("./util");
function Async() {
this._customScheduler = false;
this._isTickUsed = false;
this._lateQueue = new Queue(16);
this._normalQueue = new Queue(16);
this._haveDrainedQueues = false;
this._trampolineEnabled = true;
var self = this;
this.drainQueues = function () {
self._drainQueues();
};
this._schedule = schedule;
}
Async.prototype.setScheduler = function(fn) {
var prev = this._schedule;
this._schedule = fn;
this._customScheduler = true;
return prev;
};
Async.prototype.hasCustomScheduler = function() {
return this._customScheduler;
};
Async.prototype.enableTrampoline = function() {
this._trampolineEnabled = true;
};
Async.prototype.disableTrampolineIfNecessary = function() {
if (util.hasDevTools) {
this._trampolineEnabled = false;
}
};
Async.prototype.haveItemsQueued = function () {
return this._isTickUsed || this._haveDrainedQueues;
};
Async.prototype.fatalError = function(e, isNode) {
if (isNode) {
process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
"\n");
process.exit(2);
} else {
this.throwLater(e);
}
};
Async.prototype.throwLater = function(fn, arg) {
if (arguments.length === 1) {
arg = fn;
fn = function () { throw arg; };
}
if (typeof setTimeout !== "undefined") {
setTimeout(function() {
fn(arg);
}, 0);
} else try {
this._schedule(function() {
fn(arg);
});
} catch (e) {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
};
function AsyncInvokeLater(fn, receiver, arg) {
this._lateQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncInvoke(fn, receiver, arg) {
this._normalQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncSettlePromises(promise) {
this._normalQueue._pushOne(promise);
this._queueTick();
}
Eif (!util.hasDevTools) {
Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
});
}
};
Async.prototype.invoke = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
fn.call(receiver, arg);
});
}
};
Async.prototype.settlePromises = function(promise) {
if (this._trampolineEnabled) {
AsyncSettlePromises.call(this, promise);
} else {
this._schedule(function() {
promise._settlePromises();
});
}
};
}
Async.prototype.invokeFirst = function (fn, receiver, arg) {
this._normalQueue.unshift(fn, receiver, arg);
this._queueTick();
};
Async.prototype._drainQueue = function(queue) {
while (queue.length() > 0) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
continue;
}
var receiver = queue.shift();
var arg = queue.shift();
fn.call(receiver, arg);
}
};
Async.prototype._drainQueues = function () {
this._drainQueue(this._normalQueue);
this._reset();
this._haveDrainedQueues = true;
this._drainQueue(this._lateQueue);
};
Async.prototype._queueTick = function () {
if (!this._isTickUsed) {
this._isTickUsed = true;
this._schedule(this.drainQueues);
}
};
Async.prototype._reset = function () {
this._isTickUsed = false;
};
module.exports = Async;
module.exports.firstLineError = firstLineError;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
var calledBind = false;
var rejectThis = function(_, e) {
this._reject(e);
};
var targetRejected = function(e, context) {
context.promiseRejectionQueued = true;
context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
};
var bindingResolved = function(thisArg, context) {
if (((this._bitField & 50397184) === 0)) {
this._resolveCallback(context.target);
}
};
var bindingRejected = function(e, context) {
if (!context.promiseRejectionQueued) this._reject(e);
};
Promise.prototype.bind = function (thisArg) {
if (!calledBind) {
calledBind = true;
Promise.prototype._propagateFrom = debug.propagateFromFunction();
Promise.prototype._boundValue = debug.boundValueFunction();
}
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._propagateFrom(this, 1);
var target = this._target();
ret._setBoundTo(maybePromise);
if (maybePromise instanceof Promise) {
var context = {
promiseRejectionQueued: false,
promise: ret,
target: target,
bindingPromise: maybePromise
};
target._then(INTERNAL, targetRejected, undefined, ret, context);
maybePromise._then(
bindingResolved, bindingRejected, undefined, ret, context);
ret._setOnCancel(maybePromise);
} else {
ret._resolveCallback(target);
}
return ret;
};
Promise.prototype._setBoundTo = function (obj) {
if (obj !== undefined) {
this._bitField = this._bitField | 2097152;
this._boundTo = obj;
} else {
this._bitField = this._bitField & (~2097152);
}
};
Promise.prototype._isBound = function () {
return (this._bitField & 2097152) === 2097152;
};
Promise.bind = function (thisArg, value) {
return Promise.resolve(value).bind(thisArg);
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | 1 1 1 1 1 1 | "use strict"; var old; Eif (typeof Promise !== "undefined") old = Promise; function noConflict() { try { if (Promise === bluebird) Promise = old; } catch (e) {} return bluebird; } var bluebird = require("./promise")(); bluebird.noConflict = noConflict; module.exports = bluebird; |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict"; var cr = Object.create; Eif (cr) { var callerCache = cr(null); var getterCache = cr(null); callerCache[" size"] = getterCache[" size"] = 0; } module.exports = function(Promise) { var util = require("./util"); var canEvaluate = util.canEvaluate; var isIdentifier = util.isIdentifier; var getMethodCaller; var getGetter; Eif (!false) { var makeMethodCaller = function (methodName) { return new Function("ensureMethod", " \n\ return function(obj) { \n\ 'use strict' \n\ var len = this.length; \n\ ensureMethod(obj, 'methodName'); \n\ switch(len) { \n\ case 1: return obj.methodName(this[0]); \n\ case 2: return obj.methodName(this[0], this[1]); \n\ case 3: return obj.methodName(this[0], this[1], this[2]); \n\ case 0: return obj.methodName(); \n\ default: \n\ return obj.methodName.apply(obj, this); \n\ } \n\ }; \n\ ".replace(/methodName/g, methodName))(ensureMethod); }; var makeGetter = function (propertyName) { return new Function("obj", " \n\ 'use strict'; \n\ return obj.propertyName; \n\ ".replace("propertyName", propertyName)); }; var getCompiled = function(name, compiler, cache) { var ret = cache[name]; if (typeof ret !== "function") { if (!isIdentifier(name)) { return null; } ret = compiler(name); cache[name] = ret; cache[" size"]++; if (cache[" size"] > 512) { var keys = Object.keys(cache); for (var i = 0; i < 256; ++i) delete cache[keys[i]]; cache[" size"] = keys.length - 256; } } return ret; }; getMethodCaller = function(name) { return getCompiled(name, makeMethodCaller, callerCache); }; getGetter = function(name) { return getCompiled(name, makeGetter, getterCache); }; } function ensureMethod(obj, methodName) { var fn; if (obj != null) fn = obj[methodName]; if (typeof fn !== "function") { var message = "Object " + util.classString(obj) + " has no method '" + util.toString(methodName) + "'"; throw new Promise.TypeError(message); } return fn; } function caller(obj) { var methodName = this.pop(); var fn = ensureMethod(obj, methodName); return fn.apply(obj, this); } Promise.prototype.call = function (methodName) { var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; if (!false) { if (canEvaluate) { var maybeCaller = getMethodCaller(methodName); if (maybeCaller !== null) { return this._then( maybeCaller, undefined, undefined, args, undefined); } } } args.push(methodName); return this._then(caller, undefined, undefined, args, undefined); }; function namedGetter(obj) { return obj[this]; } function indexedGetter(obj) { var index = +this; if (index < 0) index = Math.max(0, index + obj.length); return obj[index]; } Promise.prototype.get = function (propertyName) { var isIndex = (typeof propertyName === "number"); var getter; if (!isIndex) { if (canEvaluate) { var maybeGetter = getGetter(propertyName); getter = maybeGetter !== null ? maybeGetter : namedGetter; } else { getter = namedGetter; } } else { getter = indexedGetter; } return this._then(getter, undefined, undefined, propertyName, undefined); }; }; |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise, PromiseArray, apiRejection, debug) {
var util = require("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
Promise.prototype["break"] = Promise.prototype.cancel = function() {
if (!debug.cancellation()) return this._warn("cancellation is disabled");
var promise = this;
var child = promise;
while (promise.isCancellable()) {
if (!promise._cancelBy(child)) {
if (child._isFollowing()) {
child._followee().cancel();
} else {
child._cancelBranched();
}
break;
}
var parent = promise._cancellationParent;
if (parent == null || !parent.isCancellable()) {
if (promise._isFollowing()) {
promise._followee().cancel();
} else {
promise._cancelBranched();
}
break;
} else {
if (promise._isFollowing()) promise._followee().cancel();
child = promise;
promise = parent;
}
}
};
Promise.prototype._branchHasCancelled = function() {
this._branchesRemainingToCancel--;
};
Promise.prototype._enoughBranchesHaveCancelled = function() {
return this._branchesRemainingToCancel === undefined ||
this._branchesRemainingToCancel <= 0;
};
Promise.prototype._cancelBy = function(canceller) {
if (canceller === this) {
this._branchesRemainingToCancel = 0;
this._invokeOnCancel();
return true;
} else {
this._branchHasCancelled();
if (this._enoughBranchesHaveCancelled()) {
this._invokeOnCancel();
return true;
}
}
return false;
};
Promise.prototype._cancelBranched = function() {
if (this._enoughBranchesHaveCancelled()) {
this._cancel();
}
};
Promise.prototype._cancel = function() {
if (!this.isCancellable()) return;
this._setCancelled();
async.invoke(this._cancelPromises, this, undefined);
};
Promise.prototype._cancelPromises = function() {
if (this._length() > 0) this._settlePromises();
};
Promise.prototype._unsetOnCancel = function() {
this._onCancelField = undefined;
};
Promise.prototype.isCancellable = function() {
return this.isPending() && !this.isCancelled();
};
Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
if (util.isArray(onCancelCallback)) {
for (var i = 0; i < onCancelCallback.length; ++i) {
this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
}
} else if (onCancelCallback !== undefined) {
if (typeof onCancelCallback === "function") {
if (!internalOnly) {
var e = tryCatch(onCancelCallback).call(this._boundValue());
if (e === errorObj) {
this._attachExtraTrace(e.e);
async.throwLater(e.e);
}
}
} else {
onCancelCallback._resultCancelled(this);
}
}
};
Promise.prototype._invokeOnCancel = function() {
var onCancelCallback = this._onCancel();
this._unsetOnCancel();
async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
};
Promise.prototype._invokeInternalOnCancel = function() {
if (this.isCancellable()) {
this._doInvokeOnCancel(this._onCancel(), true);
this._unsetOnCancel();
}
};
Promise.prototype._resultCancelled = function() {
this.cancel();
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 1 1 1 1 1 1 1 | "use strict";
module.exports = function(NEXT_FILTER) {
var util = require("./util");
var getKeys = require("./es5").keys;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function catchFilter(instances, cb, promise) {
return function(e) {
var boundTo = promise._boundValue();
predicateLoop: for (var i = 0; i < instances.length; ++i) {
var item = instances[i];
if (item === Error ||
(item != null && item.prototype instanceof Error)) {
if (e instanceof item) {
return tryCatch(cb).call(boundTo, e);
}
} else if (typeof item === "function") {
var matchesPredicate = tryCatch(item).call(boundTo, e);
if (matchesPredicate === errorObj) {
return matchesPredicate;
} else if (matchesPredicate) {
return tryCatch(cb).call(boundTo, e);
}
} else if (util.isObject(e)) {
var keys = getKeys(item);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
if (item[key] != e[key]) {
continue predicateLoop;
}
}
return tryCatch(cb).call(boundTo, e);
}
}
return NEXT_FILTER;
};
}
return catchFilter;
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise) {
var longStackTraces = false;
var contextStack = [];
Promise.prototype._promiseCreated = function() {};
Promise.prototype._pushContext = function() {};
Promise.prototype._popContext = function() {return null;};
Promise._peekContext = Promise.prototype._peekContext = function() {};
function Context() {
this._trace = new Context.CapturedTrace(peekContext());
}
Context.prototype._pushContext = function () {
if (this._trace !== undefined) {
this._trace._promiseCreated = null;
contextStack.push(this._trace);
}
};
Context.prototype._popContext = function () {
if (this._trace !== undefined) {
var trace = contextStack.pop();
var ret = trace._promiseCreated;
trace._promiseCreated = null;
return ret;
}
return null;
};
function createContext() {
if (longStackTraces) return new Context();
}
function peekContext() {
var lastIndex = contextStack.length - 1;
if (lastIndex >= 0) {
return contextStack[lastIndex];
}
return undefined;
}
Context.CapturedTrace = null;
Context.create = createContext;
Context.deactivateLongStackTraces = function() {};
Context.activateLongStackTraces = function() {
var Promise_pushContext = Promise.prototype._pushContext;
var Promise_popContext = Promise.prototype._popContext;
var Promise_PeekContext = Promise._peekContext;
var Promise_peekContext = Promise.prototype._peekContext;
var Promise_promiseCreated = Promise.prototype._promiseCreated;
Context.deactivateLongStackTraces = function() {
Promise.prototype._pushContext = Promise_pushContext;
Promise.prototype._popContext = Promise_popContext;
Promise._peekContext = Promise_PeekContext;
Promise.prototype._peekContext = Promise_peekContext;
Promise.prototype._promiseCreated = Promise_promiseCreated;
longStackTraces = false;
};
longStackTraces = true;
Promise.prototype._pushContext = Context.prototype._pushContext;
Promise.prototype._popContext = Context.prototype._popContext;
Promise._peekContext = Promise.prototype._peekContext = peekContext;
Promise.prototype._promiseCreated = function() {
var ctx = this._peekContext();
if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
};
};
return Context;
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 9 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 4 4 2 1 1 1 1 1 1 1 1 1 2 2 1 1 1 1 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise, Context) {
var getDomain = Promise._getDomain;
var async = Promise._async;
var Warning = require("./errors").Warning;
var util = require("./util");
var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled;
var possiblyUnhandledRejection;
var bluebirdFramePattern =
/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
var stackFramePattern = null;
var formatStack = null;
var indentStackFrames = false;
var printWarning;
var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
(false ||
util.env("BLUEBIRD_DEBUG") ||
util.env("NODE_ENV") === "development"));
var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
(debugging || util.env("BLUEBIRD_WARNINGS")));
var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
(debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
(warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
Promise.prototype.suppressUnhandledRejections = function() {
var target = this._target();
target._bitField = ((target._bitField & (~1048576)) |
524288);
};
Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 524288) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
fireRejectionEvent("rejectionHandled",
unhandledRejectionHandled, undefined, this);
};
Promise.prototype._setReturnedNonUndefined = function() {
this._bitField = this._bitField | 268435456;
};
Promise.prototype._returnedNonUndefined = function() {
return (this._bitField & 268435456) !== 0;
};
Promise.prototype._notifyUnhandledRejection = function () {
if (this._isRejectionUnhandled()) {
var reason = this._settledValue();
this._setUnhandledRejectionIsNotified();
fireRejectionEvent("unhandledRejection",
possiblyUnhandledRejection, reason, this);
}
};
Promise.prototype._setUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField | 262144;
};
Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField & (~262144);
};
Promise.prototype._isUnhandledRejectionNotified = function () {
return (this._bitField & 262144) > 0;
};
Promise.prototype._setRejectionIsUnhandled = function () {
this._bitField = this._bitField | 1048576;
};
Promise.prototype._unsetRejectionIsUnhandled = function () {
this._bitField = this._bitField & (~1048576);
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
};
Promise.prototype._isRejectionUnhandled = function () {
return (this._bitField & 1048576) > 0;
};
Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
return warn(message, shouldUseOwnTrace, promise || this);
};
Promise.onPossiblyUnhandledRejection = function (fn) {
var domain = getDomain();
possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
: undefined;
};
Promise.onUnhandledRejectionHandled = function (fn) {
var domain = getDomain();
unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
: undefined;
};
var disableLongStackTraces = function() {};
Promise.longStackTraces = function () {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (!config.longStackTraces && longStackTracesIsSupported()) {
var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
config.longStackTraces = true;
disableLongStackTraces = function() {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
Promise.prototype._captureStackTrace = Promise_captureStackTrace;
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
Context.deactivateLongStackTraces();
async.enableTrampoline();
config.longStackTraces = false;
};
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
Context.activateLongStackTraces();
async.disableTrampolineIfNecessary();
}
};
Promise.hasLongStackTraces = function () {
return config.longStackTraces && longStackTracesIsSupported();
};
var fireDomEvent = (function() {
try {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = document.createEvent("CustomEvent");
domEvent.initCustomEvent(name.toLowerCase(), false, true, event);
return !util.global.dispatchEvent(domEvent);
};
} catch (e) {}
return function() {
return false;
};
})();
var fireGlobalEvent = (function() {
Eif (util.isNode) {
return function() {
return process.emit.apply(process, arguments);
};
} else {
if (!util.global) {
return function() {
return false;
};
}
return function(name) {
var methodName = "on" + name.toLowerCase();
var method = util.global[methodName];
if (!method) return false;
method.apply(util.global, [].slice.call(arguments, 1));
return true;
};
}
})();
function generatePromiseLifecycleEventObject(name, promise) {
return {promise: promise};
}
var eventToObjectGenerator = {
promiseCreated: generatePromiseLifecycleEventObject,
promiseFulfilled: generatePromiseLifecycleEventObject,
promiseRejected: generatePromiseLifecycleEventObject,
promiseResolved: generatePromiseLifecycleEventObject,
promiseCancelled: generatePromiseLifecycleEventObject,
promiseChained: function(name, promise, child) {
return {promise: promise, child: child};
},
warning: function(name, warning) {
return {warning: warning};
},
unhandledRejection: function (name, reason, promise) {
return {reason: reason, promise: promise};
},
rejectionHandled: generatePromiseLifecycleEventObject
};
var activeFireEvent = function (name) {
var globalEventFired = false;
try {
globalEventFired = fireGlobalEvent.apply(null, arguments);
} catch (e) {
async.throwLater(e);
globalEventFired = true;
}
var domEventFired = false;
try {
domEventFired = fireDomEvent(name,
eventToObjectGenerator[name].apply(null, arguments));
} catch (e) {
async.throwLater(e);
domEventFired = true;
}
return domEventFired || globalEventFired;
};
Promise.config = function(opts) {
opts = Object(opts);
if ("longStackTraces" in opts) {
if (opts.longStackTraces) {
Promise.longStackTraces();
} else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
disableLongStackTraces();
}
}
if ("warnings" in opts) {
var warningsOption = opts.warnings;
config.warnings = !!warningsOption;
wForgottenReturn = config.warnings;
if (util.isObject(warningsOption)) {
if ("wForgottenReturn" in warningsOption) {
wForgottenReturn = !!warningsOption.wForgottenReturn;
}
}
}
if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
if (async.haveItemsQueued()) {
throw new Error(
"cannot enable cancellation after promises are in use");
}
Promise.prototype._clearCancellationData =
cancellationClearCancellationData;
Promise.prototype._propagateFrom = cancellationPropagateFrom;
Promise.prototype._onCancel = cancellationOnCancel;
Promise.prototype._setOnCancel = cancellationSetOnCancel;
Promise.prototype._attachCancellationCallback =
cancellationAttachCancellationCallback;
Promise.prototype._execute = cancellationExecute;
propagateFromFunction = cancellationPropagateFrom;
config.cancellation = true;
}
if ("monitoring" in opts) {
if (opts.monitoring && !config.monitoring) {
config.monitoring = true;
Promise.prototype._fireEvent = activeFireEvent;
} else if (!opts.monitoring && config.monitoring) {
config.monitoring = false;
Promise.prototype._fireEvent = defaultFireEvent;
}
}
};
function defaultFireEvent() { return false; }
Promise.prototype._fireEvent = defaultFireEvent;
Promise.prototype._execute = function(executor, resolve, reject) {
try {
executor(resolve, reject);
} catch (e) {
return e;
}
};
Promise.prototype._onCancel = function () {};
Promise.prototype._setOnCancel = function (handler) { ; };
Promise.prototype._attachCancellationCallback = function(onCancel) {
;
};
Promise.prototype._captureStackTrace = function () {};
Promise.prototype._attachExtraTrace = function () {};
Promise.prototype._clearCancellationData = function() {};
Promise.prototype._propagateFrom = function (parent, flags) {
;
;
};
function cancellationExecute(executor, resolve, reject) {
var promise = this;
try {
executor(resolve, reject, function(onCancel) {
if (typeof onCancel !== "function") {
throw new TypeError("onCancel must be a function, got: " +
util.toString(onCancel));
}
promise._attachCancellationCallback(onCancel);
});
} catch (e) {
return e;
}
}
function cancellationAttachCancellationCallback(onCancel) {
if (!this.isCancellable()) return this;
var previousOnCancel = this._onCancel();
if (previousOnCancel !== undefined) {
if (util.isArray(previousOnCancel)) {
previousOnCancel.push(onCancel);
} else {
this._setOnCancel([previousOnCancel, onCancel]);
}
} else {
this._setOnCancel(onCancel);
}
}
function cancellationOnCancel() {
return this._onCancelField;
}
function cancellationSetOnCancel(onCancel) {
this._onCancelField = onCancel;
}
function cancellationClearCancellationData() {
this._cancellationParent = undefined;
this._onCancelField = undefined;
}
function cancellationPropagateFrom(parent, flags) {
if ((flags & 1) !== 0) {
this._cancellationParent = parent;
var branchesRemainingToCancel = parent._branchesRemainingToCancel;
if (branchesRemainingToCancel === undefined) {
branchesRemainingToCancel = 0;
}
parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
}
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
function bindingPropagateFrom(parent, flags) {
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
var propagateFromFunction = bindingPropagateFrom;
function boundValueFunction() {
var ret = this._boundTo;
if (ret !== undefined) {
if (ret instanceof Promise) {
if (ret.isFulfilled()) {
return ret.value();
} else {
return undefined;
}
}
}
return ret;
}
function longStackTracesCaptureStackTrace() {
this._trace = new CapturedTrace(this._peekContext());
}
function longStackTracesAttachExtraTrace(error, ignoreSelf) {
if (canAttachTrace(error)) {
var trace = this._trace;
if (trace !== undefined) {
if (ignoreSelf) trace = trace._parent;
}
if (trace !== undefined) {
trace.attachExtraTrace(error);
} else if (!error.__stackCleaned__) {
var parsed = parseStackAndMessage(error);
util.notEnumerableProp(error, "stack",
parsed.message + "\n" + parsed.stack.join("\n"));
util.notEnumerableProp(error, "__stackCleaned__", true);
}
}
}
function checkForgottenReturns(returnValue, promiseCreated, name, promise,
parent) {
if (returnValue === undefined && promiseCreated !== null &&
wForgottenReturn) {
if (parent !== undefined && parent._returnedNonUndefined()) return;
if ((promise._bitField & 65535) === 0) return;
if (name) name = name + " ";
var msg = "a promise was created in a " + name +
"handler but was not returned from it";
promise._warn(msg, true, promiseCreated);
}
}
function deprecated(name, replacement) {
var message = name +
" is deprecated and will be removed in a future version.";
if (replacement) message += " Use " + replacement + " instead.";
return warn(message);
}
function warn(message, shouldUseOwnTrace, promise) {
if (!config.warnings) return;
var warning = new Warning(message);
var ctx;
if (shouldUseOwnTrace) {
promise._attachExtraTrace(warning);
} else if (config.longStackTraces && (ctx = Promise._peekContext())) {
ctx.attachExtraTrace(warning);
} else {
var parsed = parseStackAndMessage(warning);
warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
}
if (!activeFireEvent("warning", warning)) {
formatAndLogError(warning, "", true);
}
}
function reconstructStack(message, stacks) {
for (var i = 0; i < stacks.length - 1; ++i) {
stacks[i].push("From previous event:");
stacks[i] = stacks[i].join("\n");
}
if (i < stacks.length) {
stacks[i] = stacks[i].join("\n");
}
return message + "\n" + stacks.join("\n");
}
function removeDuplicateOrEmptyJumps(stacks) {
for (var i = 0; i < stacks.length; ++i) {
if (stacks[i].length === 0 ||
((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
stacks.splice(i, 1);
i--;
}
}
}
function removeCommonRoots(stacks) {
var current = stacks[0];
for (var i = 1; i < stacks.length; ++i) {
var prev = stacks[i];
var currentLastIndex = current.length - 1;
var currentLastLine = current[currentLastIndex];
var commonRootMeetPoint = -1;
for (var j = prev.length - 1; j >= 0; --j) {
if (prev[j] === currentLastLine) {
commonRootMeetPoint = j;
break;
}
}
for (var j = commonRootMeetPoint; j >= 0; --j) {
var line = prev[j];
if (current[currentLastIndex] === line) {
current.pop();
currentLastIndex--;
} else {
break;
}
}
current = prev;
}
}
function cleanStack(stack) {
var ret = [];
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
var isTraceLine = " (No stack trace)" === line ||
stackFramePattern.test(line);
var isInternalFrame = isTraceLine && shouldIgnore(line);
if (isTraceLine && !isInternalFrame) {
if (indentStackFrames && line.charAt(0) !== " ") {
line = " " + line;
}
ret.push(line);
}
}
return ret;
}
function stackFramesAsArray(error) {
var stack = error.stack.replace(/\s+$/g, "").split("\n");
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
if (" (No stack trace)" === line || stackFramePattern.test(line)) {
break;
}
}
if (i > 0) {
stack = stack.slice(i);
}
return stack;
}
function parseStackAndMessage(error) {
var stack = error.stack;
var message = error.toString();
stack = typeof stack === "string" && stack.length > 0
? stackFramesAsArray(error) : [" (No stack trace)"];
return {
message: message,
stack: cleanStack(stack)
};
}
function formatAndLogError(error, title, isSoft) {
if (typeof console !== "undefined") {
var message;
if (util.isObject(error)) {
var stack = error.stack;
message = title + formatStack(stack, error);
} else {
message = title + String(error);
}
if (typeof printWarning === "function") {
printWarning(message, isSoft);
} else if (typeof console.log === "function" ||
typeof console.log === "object") {
console.log(message);
}
}
}
function fireRejectionEvent(name, localHandler, reason, promise) {
var localEventFired = false;
try {
if (typeof localHandler === "function") {
localEventFired = true;
if (name === "rejectionHandled") {
localHandler(promise);
} else {
localHandler(reason, promise);
}
}
} catch (e) {
async.throwLater(e);
}
if (name === "unhandledRejection") {
if (!activeFireEvent(name, reason, promise) && !localEventFired) {
formatAndLogError(reason, "Unhandled rejection ");
}
} else {
activeFireEvent(name, promise);
}
}
function formatNonError(obj) {
var str;
if (typeof obj === "function") {
str = "[function " +
(obj.name || "anonymous") +
"]";
} else {
str = obj && typeof obj.toString === "function"
? obj.toString() : util.toString(obj);
var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
if (ruselessToString.test(str)) {
try {
var newStr = JSON.stringify(obj);
str = newStr;
}
catch(e) {
}
}
if (str.length === 0) {
str = "(empty array)";
}
}
return ("(<" + snip(str) + ">, no stack trace)");
}
function snip(str) {
var maxChars = 41;
if (str.length < maxChars) {
return str;
}
return str.substr(0, maxChars - 3) + "...";
}
function longStackTracesIsSupported() {
return typeof captureStackTrace === "function";
}
var shouldIgnore = function() { return false; };
var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
function parseLineInfo(line) {
var matches = line.match(parseLineInfoRegex);
if (matches) {
return {
fileName: matches[1],
line: parseInt(matches[2], 10)
};
}
}
function setBounds(firstLineError, lastLineError) {
Iif (!longStackTracesIsSupported()) return;
var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = lastLineError.stack.split("\n");
var firstIndex = -1;
var lastIndex = -1;
var firstFileName;
var lastFileName;
for (var i = 0; i < firstStackLines.length; ++i) {
var result = parseLineInfo(firstStackLines[i]);
if (result) {
firstFileName = result.fileName;
firstIndex = result.line;
break;
}
}
for (var i = 0; i < lastStackLines.length; ++i) {
var result = parseLineInfo(lastStackLines[i]);
if (result) {
lastFileName = result.fileName;
lastIndex = result.line;
break;
}
}
Eif (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
firstFileName !== lastFileName || firstIndex >= lastIndex) {
return;
}
shouldIgnore = function(line) {
if (bluebirdFramePattern.test(line)) return true;
var info = parseLineInfo(line);
if (info) {
if (info.fileName === firstFileName &&
(firstIndex <= info.line && info.line <= lastIndex)) {
return true;
}
}
return false;
};
}
function CapturedTrace(parent) {
this._parent = parent;
this._promisesCreated = 0;
var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
captureStackTrace(this, CapturedTrace);
if (length > 32) this.uncycle();
}
util.inherits(CapturedTrace, Error);
Context.CapturedTrace = CapturedTrace;
CapturedTrace.prototype.uncycle = function() {
var length = this._length;
if (length < 2) return;
var nodes = [];
var stackToIndex = {};
for (var i = 0, node = this; node !== undefined; ++i) {
nodes.push(node);
node = node._parent;
}
length = this._length = i;
for (var i = length - 1; i >= 0; --i) {
var stack = nodes[i].stack;
if (stackToIndex[stack] === undefined) {
stackToIndex[stack] = i;
}
}
for (var i = 0; i < length; ++i) {
var currentStack = nodes[i].stack;
var index = stackToIndex[currentStack];
if (index !== undefined && index !== i) {
if (index > 0) {
nodes[index - 1]._parent = undefined;
nodes[index - 1]._length = 1;
}
nodes[i]._parent = undefined;
nodes[i]._length = 1;
var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
if (index < length - 1) {
cycleEdgeNode._parent = nodes[index + 1];
cycleEdgeNode._parent.uncycle();
cycleEdgeNode._length =
cycleEdgeNode._parent._length + 1;
} else {
cycleEdgeNode._parent = undefined;
cycleEdgeNode._length = 1;
}
var currentChildLength = cycleEdgeNode._length + 1;
for (var j = i - 2; j >= 0; --j) {
nodes[j]._length = currentChildLength;
currentChildLength++;
}
return;
}
}
};
CapturedTrace.prototype.attachExtraTrace = function(error) {
if (error.__stackCleaned__) return;
this.uncycle();
var parsed = parseStackAndMessage(error);
var message = parsed.message;
var stacks = [parsed.stack];
var trace = this;
while (trace !== undefined) {
stacks.push(cleanStack(trace.stack.split("\n")));
trace = trace._parent;
}
removeCommonRoots(stacks);
removeDuplicateOrEmptyJumps(stacks);
util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
util.notEnumerableProp(error, "__stackCleaned__", true);
};
var captureStackTrace = (function stackDetection() {
var v8stackFramePattern = /^\s*at\s*/;
var v8stackFormatter = function(stack, error) {
if (typeof stack === "string") return stack;
if (error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
Eif (typeof Error.stackTraceLimit === "number" &&
typeof Error.captureStackTrace === "function") {
Error.stackTraceLimit += 6;
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
var captureStackTrace = Error.captureStackTrace;
shouldIgnore = function(line) {
return bluebirdFramePattern.test(line);
};
return function(receiver, ignoreUntil) {
Error.stackTraceLimit += 6;
captureStackTrace(receiver, ignoreUntil);
Error.stackTraceLimit -= 6;
};
}
var err = new Error();
if (typeof err.stack === "string" &&
err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
stackFramePattern = /@/;
formatStack = v8stackFormatter;
indentStackFrames = true;
return function captureStackTrace(o) {
o.stack = new Error().stack;
};
}
var hasStackAfterThrow;
try { throw new Error(); }
catch(e) {
hasStackAfterThrow = ("stack" in e);
}
if (!("stack" in err) && hasStackAfterThrow &&
typeof Error.stackTraceLimit === "number") {
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
return function captureStackTrace(o) {
Error.stackTraceLimit += 6;
try { throw new Error(); }
catch(e) { o.stack = e.stack; }
Error.stackTraceLimit -= 6;
};
}
formatStack = function(stack, error) {
if (typeof stack === "string") return stack;
if ((typeof error === "object" ||
typeof error === "function") &&
error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
return null;
})([]);
Eif (typeof console !== "undefined" && typeof console.warn !== "undefined") {
printWarning = function (message) {
console.warn(message);
};
Eif (util.isNode && process.stderr.isTTY) {
printWarning = function(message, isSoft) {
var color = isSoft ? "\u001b[33m" : "\u001b[31m";
console.warn(color + message + "\u001b[0m\n");
};
} else if (!util.isNode && typeof (new Error().stack) === "string") {
printWarning = function(message, isSoft) {
console.warn("%c" + message,
isSoft ? "color: darkorange" : "color: red");
};
}
}
var config = {
warnings: warnings,
longStackTraces: false,
cancellation: false,
monitoring: false
};
Iif (longStackTraces) Promise.longStackTraces();
return {
longStackTraces: function() {
return config.longStackTraces;
},
warnings: function() {
return config.warnings;
},
cancellation: function() {
return config.cancellation;
},
monitoring: function() {
return config.monitoring;
},
propagateFromFunction: function() {
return propagateFromFunction;
},
boundValueFunction: function() {
return boundValueFunction;
},
checkForgottenReturns: checkForgottenReturns,
setBounds: setBounds,
warn: warn,
deprecated: deprecated,
CapturedTrace: CapturedTrace,
fireDomEvent: fireDomEvent,
fireGlobalEvent: fireGlobalEvent
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise) {
function returner() {
return this.value;
}
function thrower() {
throw this.reason;
}
Promise.prototype["return"] =
Promise.prototype.thenReturn = function (value) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
returner, undefined, undefined, {value: value}, undefined);
};
Promise.prototype["throw"] =
Promise.prototype.thenThrow = function (reason) {
return this._then(
thrower, undefined, undefined, {reason: reason}, undefined);
};
Promise.prototype.catchThrow = function (reason) {
if (arguments.length <= 1) {
return this._then(
undefined, thrower, undefined, {reason: reason}, undefined);
} else {
var _reason = arguments[1];
var handler = function() {throw _reason;};
return this.caught(reason, handler);
}
};
Promise.prototype.catchReturn = function (value) {
if (arguments.length <= 1) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
undefined, returner, undefined, {value: value}, undefined);
} else {
var _value = arguments[1];
if (_value instanceof Promise) _value.suppressUnhandledRejections();
var handler = function() {return _value;};
return this.caught(value, handler);
}
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseReduce = Promise.reduce;
var PromiseAll = Promise.all;
function promiseAllThis() {
return PromiseAll(this);
}
function PromiseMapSeries(promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
}
Promise.prototype.each = function (fn) {
return this.mapSeries(fn)
._then(promiseAllThis, undefined, undefined, this, undefined);
};
Promise.prototype.mapSeries = function (fn) {
return PromiseReduce(this, fn, INTERNAL, INTERNAL);
};
Promise.each = function (promises, fn) {
return PromiseMapSeries(promises, fn)
._then(promiseAllThis, undefined, undefined, promises, undefined);
};
Promise.mapSeries = PromiseMapSeries;
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | 1 1 1 1 1 1 1 4 4 1 1 1 1 1 1 1 1 1 1 17 17 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
var es5 = require("./es5");
var Objectfreeze = es5.freeze;
var util = require("./util");
var inherits = util.inherits;
var notEnumerableProp = util.notEnumerableProp;
function subError(nameProperty, defaultMessage) {
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}
inherits(SubError, Error);
return SubError;
}
var _TypeError, _RangeError;
var Warning = subError("Warning", "warning");
var CancellationError = subError("CancellationError", "cancellation error");
var TimeoutError = subError("TimeoutError", "timeout error");
var AggregateError = subError("AggregateError", "aggregate error");
try {
_TypeError = TypeError;
_RangeError = RangeError;
} catch(e) {
_TypeError = subError("TypeError", "type error");
_RangeError = subError("RangeError", "range error");
}
var methods = ("join pop push shift unshift slice filter forEach some " +
"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
for (var i = 0; i < methods.length; ++i) {
Eif (typeof Array.prototype[methods[i]] === "function") {
AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
}
}
es5.defineProperty(AggregateError.prototype, "length", {
value: 0,
configurable: false,
writable: true,
enumerable: true
});
AggregateError.prototype["isOperational"] = true;
var level = 0;
AggregateError.prototype.toString = function() {
var indent = Array(level * 4 + 1).join(" ");
var ret = "\n" + indent + "AggregateError of:" + "\n";
level++;
indent = Array(level * 4 + 1).join(" ");
for (var i = 0; i < this.length; ++i) {
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
var lines = str.split("\n");
for (var j = 0; j < lines.length; ++j) {
lines[j] = indent + lines[j];
}
str = lines.join("\n");
ret += str + "\n";
}
level--;
return ret;
};
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(OperationalError, Error);
var errorTypes = Error["__BluebirdErrorTypes__"];
Eif (!errorTypes) {
errorTypes = Objectfreeze({
CancellationError: CancellationError,
TimeoutError: TimeoutError,
OperationalError: OperationalError,
RejectionError: OperationalError,
AggregateError: AggregateError
});
es5.defineProperty(Error, "__BluebirdErrorTypes__", {
value: errorTypes,
writable: false,
enumerable: false,
configurable: false
});
}
module.exports = {
Error: Error,
TypeError: _TypeError,
RangeError: _RangeError,
CancellationError: errorTypes.CancellationError,
OperationalError: errorTypes.OperationalError,
TimeoutError: errorTypes.TimeoutError,
AggregateError: errorTypes.AggregateError,
Warning: Warning
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | 1 1 1 1 | var isES5 = (function(){
"use strict";
return this === undefined;
})();
Eif (isES5) {
module.exports = {
freeze: Object.freeze,
defineProperty: Object.defineProperty,
getDescriptor: Object.getOwnPropertyDescriptor,
keys: Object.keys,
names: Object.getOwnPropertyNames,
getPrototypeOf: Object.getPrototypeOf,
isArray: Array.isArray,
isES5: isES5,
propertyIsWritable: function(obj, prop) {
var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
return !!(!descriptor || descriptor.writable || descriptor.set);
}
};
} else {
var has = {}.hasOwnProperty;
var str = {}.toString;
var proto = {}.constructor.prototype;
var ObjectKeys = function (o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
ret.push(key);
}
}
return ret;
};
var ObjectGetDescriptor = function(o, key) {
return {value: o[key]};
};
var ObjectDefineProperty = function (o, key, desc) {
o[key] = desc.value;
return o;
};
var ObjectFreeze = function (obj) {
return obj;
};
var ObjectGetPrototypeOf = function (obj) {
try {
return Object(obj).constructor.prototype;
}
catch (e) {
return proto;
}
};
var ArrayIsArray = function (obj) {
try {
return str.call(obj) === "[object Array]";
}
catch(e) {
return false;
}
};
module.exports = {
isArray: ArrayIsArray,
keys: ObjectKeys,
names: ObjectKeys,
defineProperty: ObjectDefineProperty,
getDescriptor: ObjectGetDescriptor,
freeze: ObjectFreeze,
getPrototypeOf: ObjectGetPrototypeOf,
isES5: isES5,
propertyIsWritable: function() {
return true;
}
};
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 1 1 1 1 | "use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseMap = Promise.map;
Promise.prototype.filter = function (fn, options) {
return PromiseMap(this, fn, options, INTERNAL);
};
Promise.filter = function (promises, fn, options) {
return PromiseMap(promises, fn, options, INTERNAL);
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise, tryConvertToPromise) {
var util = require("./util");
var CancellationError = Promise.CancellationError;
var errorObj = util.errorObj;
function PassThroughHandlerContext(promise, type, handler) {
this.promise = promise;
this.type = type;
this.handler = handler;
this.called = false;
this.cancelPromise = null;
}
PassThroughHandlerContext.prototype.isFinallyHandler = function() {
return this.type === 0;
};
function FinallyHandlerCancelReaction(finallyHandler) {
this.finallyHandler = finallyHandler;
}
FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
checkCancel(this.finallyHandler);
};
function checkCancel(ctx, reason) {
if (ctx.cancelPromise != null) {
if (arguments.length > 1) {
ctx.cancelPromise._reject(reason);
} else {
ctx.cancelPromise._cancel();
}
ctx.cancelPromise = null;
return true;
}
return false;
}
function succeed() {
return finallyHandler.call(this, this.promise._target()._settledValue());
}
function fail(reason) {
if (checkCancel(this, reason)) return;
errorObj.e = reason;
return errorObj;
}
function finallyHandler(reasonOrValue) {
var promise = this.promise;
var handler = this.handler;
if (!this.called) {
this.called = true;
var ret = this.isFinallyHandler()
? handler.call(promise._boundValue())
: handler.call(promise._boundValue(), reasonOrValue);
if (ret !== undefined) {
promise._setReturnedNonUndefined();
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
if (this.cancelPromise != null) {
if (maybePromise.isCancelled()) {
var reason =
new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
errorObj.e = reason;
return errorObj;
} else if (maybePromise.isPending()) {
maybePromise._attachCancellationCallback(
new FinallyHandlerCancelReaction(this));
}
}
return maybePromise._then(
succeed, fail, undefined, this, undefined);
}
}
}
if (promise.isRejected()) {
checkCancel(this);
errorObj.e = reasonOrValue;
return errorObj;
} else {
checkCancel(this);
return reasonOrValue;
}
}
Promise.prototype._passThrough = function(handler, type, success, fail) {
if (typeof handler !== "function") return this.then();
return this._then(success,
fail,
undefined,
new PassThroughHandlerContext(this, type, handler),
undefined);
};
Promise.prototype.lastly =
Promise.prototype["finally"] = function (handler) {
return this._passThrough(handler,
0,
finallyHandler,
finallyHandler);
};
Promise.prototype.tap = function (handler) {
return this._passThrough(handler, 1, finallyHandler);
};
return PassThroughHandlerContext;
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise,
apiRejection,
INTERNAL,
tryConvertToPromise,
Proxyable,
debug) {
var errors = require("./errors");
var TypeError = errors.TypeError;
var util = require("./util");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var yieldHandlers = [];
function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
for (var i = 0; i < yieldHandlers.length; ++i) {
traceParent._pushContext();
var result = tryCatch(yieldHandlers[i])(value);
traceParent._popContext();
if (result === errorObj) {
traceParent._pushContext();
var ret = Promise.reject(errorObj.e);
traceParent._popContext();
return ret;
}
var maybePromise = tryConvertToPromise(result, traceParent);
if (maybePromise instanceof Promise) return maybePromise;
}
return null;
}
function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
if (debug.cancellation()) {
var internal = new Promise(INTERNAL);
var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
this._promise = internal.lastly(function() {
return _finallyPromise;
});
internal._captureStackTrace();
internal._setOnCancel(this);
} else {
var promise = this._promise = new Promise(INTERNAL);
promise._captureStackTrace();
}
this._stack = stack;
this._generatorFunction = generatorFunction;
this._receiver = receiver;
this._generator = undefined;
this._yieldHandlers = typeof yieldHandler === "function"
? [yieldHandler].concat(yieldHandlers)
: yieldHandlers;
this._yieldedPromise = null;
this._cancellationPhase = false;
}
util.inherits(PromiseSpawn, Proxyable);
PromiseSpawn.prototype._isResolved = function() {
return this._promise === null;
};
PromiseSpawn.prototype._cleanup = function() {
this._promise = this._generator = null;
if (debug.cancellation() && this._finallyPromise !== null) {
this._finallyPromise._fulfill();
this._finallyPromise = null;
}
};
PromiseSpawn.prototype._promiseCancelled = function() {
if (this._isResolved()) return;
var implementsReturn = typeof this._generator["return"] !== "undefined";
var result;
if (!implementsReturn) {
var reason = new Promise.CancellationError(
"generator .return() sentinel");
Promise.coroutine.returnSentinel = reason;
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
result = tryCatch(this._generator["throw"]).call(this._generator,
reason);
this._promise._popContext();
} else {
this._promise._pushContext();
result = tryCatch(this._generator["return"]).call(this._generator,
undefined);
this._promise._popContext();
}
this._cancellationPhase = true;
this._yieldedPromise = null;
this._continue(result);
};
PromiseSpawn.prototype._promiseFulfilled = function(value) {
this._yieldedPromise = null;
this._promise._pushContext();
var result = tryCatch(this._generator.next).call(this._generator, value);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._promiseRejected = function(reason) {
this._yieldedPromise = null;
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
var result = tryCatch(this._generator["throw"])
.call(this._generator, reason);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._resultCancelled = function() {
if (this._yieldedPromise instanceof Promise) {
var promise = this._yieldedPromise;
this._yieldedPromise = null;
promise.cancel();
}
};
PromiseSpawn.prototype.promise = function () {
return this._promise;
};
PromiseSpawn.prototype._run = function () {
this._generator = this._generatorFunction.call(this._receiver);
this._receiver =
this._generatorFunction = undefined;
this._promiseFulfilled(undefined);
};
PromiseSpawn.prototype._continue = function (result) {
var promise = this._promise;
if (result === errorObj) {
this._cleanup();
if (this._cancellationPhase) {
return promise.cancel();
} else {
return promise._rejectCallback(result.e, false);
}
}
var value = result.value;
if (result.done === true) {
this._cleanup();
if (this._cancellationPhase) {
return promise.cancel();
} else {
return promise._resolveCallback(value);
}
} else {
var maybePromise = tryConvertToPromise(value, this._promise);
if (!(maybePromise instanceof Promise)) {
maybePromise =
promiseFromYieldHandler(maybePromise,
this._yieldHandlers,
this._promise);
if (maybePromise === null) {
this._promiseRejected(
new TypeError(
"A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
"From coroutine:\u000a" +
this._stack.split("\n").slice(1, -7).join("\n")
)
);
return;
}
}
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
this._yieldedPromise = maybePromise;
maybePromise._proxy(this, null);
} else if (((bitField & 33554432) !== 0)) {
this._promiseFulfilled(maybePromise._value());
} else if (((bitField & 16777216) !== 0)) {
this._promiseRejected(maybePromise._reason());
} else {
this._promiseCancelled();
}
}
};
Promise.coroutine = function (generatorFunction, options) {
if (typeof generatorFunction !== "function") {
throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var yieldHandler = Object(options).yieldHandler;
var PromiseSpawn$ = PromiseSpawn;
var stack = new Error().stack;
return function () {
var generator = generatorFunction.apply(this, arguments);
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
stack);
var ret = spawn.promise();
spawn._generator = generator;
spawn._promiseFulfilled(undefined);
return ret;
};
};
Promise.coroutine.addYieldHandler = function(fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
yieldHandlers.push(fn);
};
Promise.spawn = function (generatorFunction) {
debug.deprecated("Promise.spawn()", "Promise.coroutine()");
if (typeof generatorFunction !== "function") {
return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var spawn = new PromiseSpawn(generatorFunction, this);
var ret = spawn.promise();
spawn._run(Promise.spawn);
return ret;
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | 1 1 1 1 1 1 1 1 1 8 1 8 1 8 8 36 8 8 36 8 8 8 8 8 1 1 1 1 8 8 8 1 1 | "use strict";
module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
var util = require("./util");
var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var reject;
Eif (!false) {
Eif (canEvaluate) {
var thenCallback = function(i) {
return new Function("value", "holder", " \n\
'use strict'; \n\
holder.pIndex = value; \n\
holder.checkFulfillment(this); \n\
".replace(/Index/g, i));
};
var promiseSetter = function(i) {
return new Function("promise", "holder", " \n\
'use strict'; \n\
holder.pIndex = promise; \n\
".replace(/Index/g, i));
};
var generateHolderClass = function(total) {
var props = new Array(total);
for (var i = 0; i < props.length; ++i) {
props[i] = "this.p" + (i+1);
}
var assignment = props.join(" = ") + " = null;";
var cancellationCode= "var promise;\n" + props.map(function(prop) {
return " \n\
promise = " + prop + "; \n\
if (promise instanceof Promise) { \n\
promise.cancel(); \n\
} \n\
";
}).join("\n");
var passedArguments = props.join(", ");
var name = "Holder$" + total;
var code = "return function(tryCatch, errorObj, Promise) { \n\
'use strict'; \n\
function [TheName](fn) { \n\
[TheProperties] \n\
this.fn = fn; \n\
this.now = 0; \n\
} \n\
[TheName].prototype.checkFulfillment = function(promise) { \n\
var now = ++this.now; \n\
if (now === [TheTotal]) { \n\
promise._pushContext(); \n\
var callback = this.fn; \n\
var ret = tryCatch(callback)([ThePassedArguments]); \n\
promise._popContext(); \n\
if (ret === errorObj) { \n\
promise._rejectCallback(ret.e, false); \n\
} else { \n\
promise._resolveCallback(ret); \n\
} \n\
} \n\
}; \n\
\n\
[TheName].prototype._resultCancelled = function() { \n\
[CancellationCode] \n\
}; \n\
\n\
return [TheName]; \n\
}(tryCatch, errorObj, Promise); \n\
";
code = code.replace(/\[TheName\]/g, name)
.replace(/\[TheTotal\]/g, total)
.replace(/\[ThePassedArguments\]/g, passedArguments)
.replace(/\[TheProperties\]/g, assignment)
.replace(/\[CancellationCode\]/g, cancellationCode);
return new Function("tryCatch", "errorObj", "Promise", code)
(tryCatch, errorObj, Promise);
};
var holderClasses = [];
var thenCallbacks = [];
var promiseSetters = [];
for (var i = 0; i < 8; ++i) {
holderClasses.push(generateHolderClass(i + 1));
thenCallbacks.push(thenCallback(i + 1));
promiseSetters.push(promiseSetter(i + 1));
}
reject = function (reason) {
this._reject(reason);
};
}}
Promise.join = function () {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (!false) {
if (last <= 8 && canEvaluate) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var HolderClass = holderClasses[last - 1];
var holder = new HolderClass(fn);
var callbacks = thenCallbacks;
for (var i = 0; i < last; ++i) {
var maybePromise = tryConvertToPromise(arguments[i], ret);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
maybePromise._then(callbacks[i], reject,
undefined, ret, holder);
promiseSetters[i](maybePromise, holder);
} else if (((bitField & 33554432) !== 0)) {
callbacks[i].call(ret,
maybePromise._value(), holder);
} else if (((bitField & 16777216) !== 0)) {
ret._reject(maybePromise._reason());
} else {
ret._cancel();
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
if (!ret._isFateSealed()) {
ret._setAsyncGuaranteed();
ret._setOnCancel(holder);
}
return ret;
}
}
}
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
if (fn) args.pop();
var ret = new PromiseArray(args).promise();
return fn !== undefined ? ret.spread(fn) : ret;
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL,
debug) {
var getDomain = Promise._getDomain;
var util = require("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var EMPTY_ARRAY = [];
function MappingPromiseArray(promises, fn, limit, _filter) {
this.constructor$(promises);
this._promise._captureStackTrace();
var domain = getDomain();
this._callback = domain === null ? fn : domain.bind(fn);
this._preservedValues = _filter === INTERNAL
? new Array(this.length())
: null;
this._limit = limit;
this._inFlight = 0;
this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
this._init$(undefined, -2);
}
util.inherits(MappingPromiseArray, PromiseArray);
MappingPromiseArray.prototype._init = function () {};
MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
var length = this.length();
var preservedValues = this._preservedValues;
var limit = this._limit;
if (index < 0) {
index = (index * -1) - 1;
values[index] = value;
if (limit >= 1) {
this._inFlight--;
this._drainQueue();
if (this._isResolved()) return true;
}
} else {
if (limit >= 1 && this._inFlight >= limit) {
values[index] = value;
this._queue.push(index);
return false;
}
if (preservedValues !== null) preservedValues[index] = value;
var promise = this._promise;
var callback = this._callback;
var receiver = promise._boundValue();
promise._pushContext();
var ret = tryCatch(callback).call(receiver, value, index, length);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret,
promiseCreated,
preservedValues !== null ? "Promise.filter" : "Promise.map",
promise
);
if (ret === errorObj) {
this._reject(ret.e);
return true;
}
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
if (limit >= 1) this._inFlight++;
values[index] = maybePromise;
maybePromise._proxy(this, (index + 1) * -1);
return false;
} else if (((bitField & 33554432) !== 0)) {
ret = maybePromise._value();
} else if (((bitField & 16777216) !== 0)) {
this._reject(maybePromise._reason());
return true;
} else {
this._cancel();
return true;
}
}
values[index] = ret;
}
var totalResolved = ++this._totalResolved;
if (totalResolved >= length) {
if (preservedValues !== null) {
this._filter(values, preservedValues);
} else {
this._resolve(values);
}
return true;
}
return false;
};
MappingPromiseArray.prototype._drainQueue = function () {
var queue = this._queue;
var limit = this._limit;
var values = this._values;
while (queue.length > 0 && this._inFlight < limit) {
if (this._isResolved()) return;
var index = queue.pop();
this._promiseFulfilled(values[index], index);
}
};
MappingPromiseArray.prototype._filter = function (booleans, values) {
var len = values.length;
var ret = new Array(len);
var j = 0;
for (var i = 0; i < len; ++i) {
if (booleans[i]) ret[j++] = values[i];
}
ret.length = j;
this._resolve(ret);
};
MappingPromiseArray.prototype.preservedValues = function () {
return this._preservedValues;
};
function map(promises, fn, options, _filter) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var limit = 0;
if (options !== undefined) {
if (typeof options === "object" && options !== null) {
if (typeof options.concurrency !== "number") {
return Promise.reject(
new TypeError("'concurrency' must be a number but it is " +
util.classString(options.concurrency)));
}
limit = options.concurrency;
} else {
return Promise.reject(new TypeError(
"options argument must be an object but it is " +
util.classString(options)));
}
}
limit = typeof limit === "number" &&
isFinite(limit) && limit >= 1 ? limit : 0;
return new MappingPromiseArray(promises, fn, limit, _filter).promise();
}
Promise.prototype.map = function (fn, options) {
return map(this, fn, options, null);
};
Promise.map = function (promises, fn, options, _filter) {
return map(promises, fn, options, _filter);
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | 1 1 1 1 1 1 | "use strict";
module.exports =
function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
var util = require("./util");
var tryCatch = util.tryCatch;
Promise.method = function (fn) {
if (typeof fn !== "function") {
throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
}
return function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.method", ret);
ret._resolveFromSyncValue(value);
return ret;
};
};
Promise.attempt = Promise["try"] = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value;
if (arguments.length > 1) {
debug.deprecated("calling Promise.try with more than 1 argument");
var arg = arguments[1];
var ctx = arguments[2];
value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
: tryCatch(fn).call(ctx, arg);
} else {
value = tryCatch(fn)();
}
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.try", ret);
ret._resolveFromSyncValue(value);
return ret;
};
Promise.prototype._resolveFromSyncValue = function (value) {
if (value === util.errorObj) {
this._rejectCallback(value.e, false);
} else {
this._resolveCallback(value, true);
}
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | 1 1 1 1 1 1 1 1 1 1 | "use strict";
var util = require("./util");
var maybeWrapAsError = util.maybeWrapAsError;
var errors = require("./errors");
var OperationalError = errors.OperationalError;
var es5 = require("./es5");
function isUntypedError(obj) {
return obj instanceof Error &&
es5.getPrototypeOf(obj) === Error.prototype;
}
var rErrorKey = /^(?:name|message|stack|cause)$/;
function wrapAsOperationalError(obj) {
var ret;
if (isUntypedError(obj)) {
ret = new OperationalError(obj);
ret.name = obj.name;
ret.message = obj.message;
ret.stack = obj.stack;
var keys = es5.keys(obj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!rErrorKey.test(key)) {
ret[key] = obj[key];
}
}
return ret;
}
util.markAsOriginatingFromRejection(obj);
return obj;
}
function nodebackForPromise(promise, multiArgs) {
return function(err, value) {
if (promise === null) return;
if (err) {
var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
promise._attachExtraTrace(wrapped);
promise._reject(wrapped);
} else if (!multiArgs) {
promise._fulfill(value);
} else {
var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
promise._fulfill(args);
}
promise = null;
};
}
module.exports = nodebackForPromise;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise) {
var util = require("./util");
var async = Promise._async;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function spreadAdapter(val, nodeback) {
var promise = this;
if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
var ret =
tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function successAdapter(val, nodeback) {
var promise = this;
var receiver = promise._boundValue();
var ret = val === undefined
? tryCatch(nodeback).call(receiver, null)
: tryCatch(nodeback).call(receiver, null, val);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function errorAdapter(reason, nodeback) {
var promise = this;
if (!reason) {
var newReason = new Error(reason + "");
newReason.cause = reason;
reason = newReason;
}
var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
options) {
if (typeof nodeback == "function") {
var adapter = successAdapter;
if (options !== undefined && Object(options).spread) {
adapter = spreadAdapter;
}
this._then(
adapter,
errorAdapter,
undefined,
this,
nodeback
);
}
return this;
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 9 9 9 9 9 9 9 9 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 8 8 8 8 8 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function() {
var makeSelfResolutionError = function () {
return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
};
var reflectHandler = function() {
return new Promise.PromiseInspection(this._target());
};
var apiRejection = function(msg) {
return Promise.reject(new TypeError(msg));
};
function Proxyable() {}
var UNDEFINED_BINDING = {};
var util = require("./util");
var getDomain;
Eif (util.isNode) {
getDomain = function() {
var ret = process.domain;
if (ret === undefined) ret = null;
return ret;
};
} else {
getDomain = function() {
return null;
};
}
util.notEnumerableProp(Promise, "_getDomain", getDomain);
var es5 = require("./es5");
var Async = require("./async");
var async = new Async();
es5.defineProperty(Promise, "_async", {value: async});
var errors = require("./errors");
var TypeError = Promise.TypeError = errors.TypeError;
Promise.RangeError = errors.RangeError;
var CancellationError = Promise.CancellationError = errors.CancellationError;
Promise.TimeoutError = errors.TimeoutError;
Promise.OperationalError = errors.OperationalError;
Promise.RejectionError = errors.OperationalError;
Promise.AggregateError = errors.AggregateError;
var INTERNAL = function(){};
var APPLY = {};
var NEXT_FILTER = {};
var tryConvertToPromise = require("./thenables")(Promise, INTERNAL);
var PromiseArray =
require("./promise_array")(Promise, INTERNAL,
tryConvertToPromise, apiRejection, Proxyable);
var Context = require("./context")(Promise);
/*jshint unused:false*/
var createContext = Context.create;
var debug = require("./debuggability")(Promise, Context);
var CapturedTrace = debug.CapturedTrace;
var PassThroughHandlerContext =
require("./finally")(Promise, tryConvertToPromise);
var catchFilter = require("./catch_filter")(NEXT_FILTER);
var nodebackForPromise = require("./nodeback");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function check(self, executor) {
if (typeof executor !== "function") {
throw new TypeError("expecting a function but got " + util.classString(executor));
}
if (self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
}
function Promise(executor) {
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
Iif (executor !== INTERNAL) {
check(this, executor);
this._resolveFromExecutor(executor);
}
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return apiRejection("expecting an object but got " + util.classString(item));
}
}
catchInstances.length = j;
fn = arguments[i];
return this.then(undefined, catchFilter(catchInstances, fn, this));
}
return this.then(undefined, fn);
};
Promise.prototype.reflect = function () {
return this._then(reflectHandler,
reflectHandler, undefined, this, undefined);
};
Promise.prototype.then = function (didFulfill, didReject) {
if (debug.warnings() && arguments.length > 0 &&
typeof didFulfill !== "function" &&
typeof didReject !== "function") {
var msg = ".then() only accepts functions but was passed: " +
util.classString(didFulfill);
if (arguments.length > 1) {
msg += ", " + util.classString(didReject);
}
this._warn(msg);
}
return this._then(didFulfill, didReject, undefined, undefined, undefined);
};
Promise.prototype.done = function (didFulfill, didReject) {
var promise =
this._then(didFulfill, didReject, undefined, undefined, undefined);
promise._setIsFinal();
};
Promise.prototype.spread = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
return this.all()._then(fn, undefined, undefined, APPLY, undefined);
};
Promise.prototype.toJSON = function () {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: undefined,
rejectionReason: undefined
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this.value();
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this.reason();
ret.isRejected = true;
}
return ret;
};
Promise.prototype.all = function () {
if (arguments.length > 0) {
this._warn(".all() was passed arguments but it does not take any");
}
return new PromiseArray(this).promise();
};
Promise.prototype.error = function (fn) {
return this.caught(util.originatesFromRejection, fn);
};
Promise.getNewLibraryCopy = module.exports;
Promise.is = function (val) {
return val instanceof Promise;
};
Promise.fromNode = Promise.fromCallback = function(fn) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
: false;
var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
if (result === errorObj) {
ret._rejectCallback(result.e, true);
}
if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
return ret;
};
Promise.all = function (promises) {
return new PromiseArray(promises).promise();
};
Promise.cast = function (obj) {
var ret = tryConvertToPromise(obj);
if (!(ret instanceof Promise)) {
ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._setFulfilled();
ret._rejectionHandler0 = obj;
}
return ret;
};
Promise.resolve = Promise.fulfilled = Promise.cast;
Promise.reject = Promise.rejected = function (reason) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._rejectCallback(reason, true);
return ret;
};
Promise.setScheduler = function(fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
return async.setScheduler(fn);
};
Promise.prototype._then = function (
didFulfill,
didReject,
_, receiver,
internalData
) {
var haveInternalData = internalData !== undefined;
var promise = haveInternalData ? internalData : new Promise(INTERNAL);
var target = this._target();
var bitField = target._bitField;
if (!haveInternalData) {
promise._propagateFrom(this, 3);
promise._captureStackTrace();
if (receiver === undefined &&
((this._bitField & 2097152) !== 0)) {
if (!((bitField & 50397184) === 0)) {
receiver = this._boundValue();
} else {
receiver = target === this ? undefined : this._boundTo;
}
}
this._fireEvent("promiseChained", this, promise);
}
var domain = getDomain();
if (!((bitField & 50397184) === 0)) {
var handler, value, settler = target._settlePromiseCtx;
if (((bitField & 33554432) !== 0)) {
value = target._rejectionHandler0;
handler = didFulfill;
} else if (((bitField & 16777216) !== 0)) {
value = target._fulfillmentHandler0;
handler = didReject;
target._unsetRejectionIsUnhandled();
} else {
settler = target._settlePromiseLateCancellationObserver;
value = new CancellationError("late cancellation observer");
target._attachExtraTrace(value);
handler = didReject;
}
async.invoke(settler, target, {
handler: domain === null ? handler
: (typeof handler === "function" && domain.bind(handler)),
promise: promise,
receiver: receiver,
value: value
});
} else {
target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
}
return promise;
};
Promise.prototype._length = function () {
return this._bitField & 65535;
};
Promise.prototype._isFateSealed = function () {
return (this._bitField & 117506048) !== 0;
};
Promise.prototype._isFollowing = function () {
return (this._bitField & 67108864) === 67108864;
};
Promise.prototype._setLength = function (len) {
this._bitField = (this._bitField & -65536) |
(len & 65535);
};
Promise.prototype._setFulfilled = function () {
this._bitField = this._bitField | 33554432;
this._fireEvent("promiseFulfilled", this);
};
Promise.prototype._setRejected = function () {
this._bitField = this._bitField | 16777216;
this._fireEvent("promiseRejected", this);
};
Promise.prototype._setFollowing = function () {
this._bitField = this._bitField | 67108864;
this._fireEvent("promiseResolved", this);
};
Promise.prototype._setIsFinal = function () {
this._bitField = this._bitField | 4194304;
};
Promise.prototype._isFinal = function () {
return (this._bitField & 4194304) > 0;
};
Promise.prototype._unsetCancelled = function() {
this._bitField = this._bitField & (~65536);
};
Promise.prototype._setCancelled = function() {
this._bitField = this._bitField | 65536;
this._fireEvent("promiseCancelled", this);
};
Promise.prototype._setAsyncGuaranteed = function() {
if (async.hasCustomScheduler()) return;
this._bitField = this._bitField | 134217728;
};
Promise.prototype._receiverAt = function (index) {
var ret = index === 0 ? this._receiver0 : this[
index * 4 - 4 + 3];
if (ret === UNDEFINED_BINDING) {
return undefined;
} else if (ret === undefined && this._isBound()) {
return this._boundValue();
}
return ret;
};
Promise.prototype._promiseAt = function (index) {
return this[
index * 4 - 4 + 2];
};
Promise.prototype._fulfillmentHandlerAt = function (index) {
return this[
index * 4 - 4 + 0];
};
Promise.prototype._rejectionHandlerAt = function (index) {
return this[
index * 4 - 4 + 1];
};
Promise.prototype._boundValue = function() {};
Promise.prototype._migrateCallback0 = function (follower) {
var bitField = follower._bitField;
var fulfill = follower._fulfillmentHandler0;
var reject = follower._rejectionHandler0;
var promise = follower._promise0;
var receiver = follower._receiverAt(0);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._migrateCallbackAt = function (follower, index) {
var fulfill = follower._fulfillmentHandlerAt(index);
var reject = follower._rejectionHandlerAt(index);
var promise = follower._promiseAt(index);
var receiver = follower._receiverAt(index);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._addCallbacks = function (
fulfill,
reject,
promise,
receiver,
domain
) {
var index = this._length();
if (index >= 65535 - 4) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
this._receiver0 = receiver;
if (typeof fulfill === "function") {
this._fulfillmentHandler0 =
domain === null ? fulfill : domain.bind(fulfill);
}
if (typeof reject === "function") {
this._rejectionHandler0 =
domain === null ? reject : domain.bind(reject);
}
} else {
var base = index * 4 - 4;
this[base + 2] = promise;
this[base + 3] = receiver;
if (typeof fulfill === "function") {
this[base + 0] =
domain === null ? fulfill : domain.bind(fulfill);
}
if (typeof reject === "function") {
this[base + 1] =
domain === null ? reject : domain.bind(reject);
}
}
this._setLength(index + 1);
return index;
};
Promise.prototype._proxy = function (proxyable, arg) {
this._addCallbacks(undefined, undefined, arg, proxyable, null);
};
Promise.prototype._resolveCallback = function(value, shouldBind) {
if (((this._bitField & 117506048) !== 0)) return;
if (value === this)
return this._rejectCallback(makeSelfResolutionError(), false);
var maybePromise = tryConvertToPromise(value, this);
if (!(maybePromise instanceof Promise)) return this._fulfill(value);
if (shouldBind) this._propagateFrom(maybePromise, 2);
var promise = maybePromise._target();
if (promise === this) {
this._reject(makeSelfResolutionError());
return;
}
var bitField = promise._bitField;
if (((bitField & 50397184) === 0)) {
var len = this._length();
if (len > 0) promise._migrateCallback0(this);
for (var i = 1; i < len; ++i) {
promise._migrateCallbackAt(this, i);
}
this._setFollowing();
this._setLength(0);
this._setFollowee(promise);
} else if (((bitField & 33554432) !== 0)) {
this._fulfill(promise._value());
} else if (((bitField & 16777216) !== 0)) {
this._reject(promise._reason());
} else {
var reason = new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
this._reject(reason);
}
};
Promise.prototype._rejectCallback =
function(reason, synchronous, ignoreNonErrorWarnings) {
var trace = util.ensureErrorObject(reason);
var hasStack = trace === reason;
if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
var message = "a promise was rejected with a non-error: " +
util.classString(reason);
this._warn(message, true);
}
this._attachExtraTrace(trace, synchronous ? hasStack : false);
this._reject(reason);
};
Promise.prototype._resolveFromExecutor = function (executor) {
var promise = this;
this._captureStackTrace();
this._pushContext();
var synchronous = true;
var r = this._execute(executor, function(value) {
promise._resolveCallback(value);
}, function (reason) {
promise._rejectCallback(reason, synchronous);
});
synchronous = false;
this._popContext();
if (r !== undefined) {
promise._rejectCallback(r, true);
}
};
Promise.prototype._settlePromiseFromHandler = function (
handler, receiver, value, promise
) {
var bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
promise._pushContext();
var x;
if (receiver === APPLY) {
if (!value || typeof value.length !== "number") {
x = errorObj;
x.e = new TypeError("cannot .spread() a non-array: " +
util.classString(value));
} else {
x = tryCatch(handler).apply(this._boundValue(), value);
}
} else {
x = tryCatch(handler).call(receiver, value);
}
var promiseCreated = promise._popContext();
bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
if (x === NEXT_FILTER) {
promise._reject(value);
} else if (x === errorObj) {
promise._rejectCallback(x.e, false);
} else {
debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
promise._resolveCallback(x);
}
};
Promise.prototype._target = function() {
var ret = this;
while (ret._isFollowing()) ret = ret._followee();
return ret;
};
Promise.prototype._followee = function() {
return this._rejectionHandler0;
};
Promise.prototype._setFollowee = function(promise) {
this._rejectionHandler0 = promise;
};
Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
var isPromise = promise instanceof Promise;
var bitField = this._bitField;
var asyncGuaranteed = ((bitField & 134217728) !== 0);
if (((bitField & 65536) !== 0)) {
if (isPromise) promise._invokeInternalOnCancel();
if (receiver instanceof PassThroughHandlerContext &&
receiver.isFinallyHandler()) {
receiver.cancelPromise = promise;
if (tryCatch(handler).call(receiver, value) === errorObj) {
promise._reject(errorObj.e);
}
} else if (handler === reflectHandler) {
promise._fulfill(reflectHandler.call(receiver));
} else if (receiver instanceof Proxyable) {
receiver._promiseCancelled(promise);
} else if (isPromise || promise instanceof PromiseArray) {
promise._cancel();
} else {
receiver.cancel();
}
} else if (typeof handler === "function") {
if (!isPromise) {
handler.call(receiver, value, promise);
} else {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (receiver instanceof Proxyable) {
if (!receiver._isResolved()) {
if (((bitField & 33554432) !== 0)) {
receiver._promiseFulfilled(value, promise);
} else {
receiver._promiseRejected(value, promise);
}
}
} else if (isPromise) {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
if (((bitField & 33554432) !== 0)) {
promise._fulfill(value);
} else {
promise._reject(value);
}
}
};
Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
var handler = ctx.handler;
var promise = ctx.promise;
var receiver = ctx.receiver;
var value = ctx.value;
if (typeof handler === "function") {
if (!(promise instanceof Promise)) {
handler.call(receiver, value, promise);
} else {
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (promise instanceof Promise) {
promise._reject(value);
}
};
Promise.prototype._settlePromiseCtx = function(ctx) {
this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
};
Promise.prototype._settlePromise0 = function(handler, value, bitField) {
var promise = this._promise0;
var receiver = this._receiverAt(0);
this._promise0 = undefined;
this._receiver0 = undefined;
this._settlePromise(promise, handler, receiver, value);
};
Promise.prototype._clearCallbackDataAtIndex = function(index) {
var base = index * 4 - 4;
this[base + 2] =
this[base + 3] =
this[base + 0] =
this[base + 1] = undefined;
};
Promise.prototype._fulfill = function (value) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
if (value === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._reject(err);
}
this._setFulfilled();
this._rejectionHandler0 = value;
if ((bitField & 65535) > 0) {
if (((bitField & 134217728) !== 0)) {
this._settlePromises();
} else {
async.settlePromises(this);
}
}
};
Promise.prototype._reject = function (reason) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
this._setRejected();
this._fulfillmentHandler0 = reason;
if (this._isFinal()) {
return async.fatalError(reason, util.isNode);
}
if ((bitField & 65535) > 0) {
async.settlePromises(this);
} else {
this._ensurePossibleRejectionHandled();
}
};
Promise.prototype._fulfillPromises = function (len, value) {
for (var i = 1; i < len; i++) {
var handler = this._fulfillmentHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, value);
}
};
Promise.prototype._rejectPromises = function (len, reason) {
for (var i = 1; i < len; i++) {
var handler = this._rejectionHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, reason);
}
};
Promise.prototype._settlePromises = function () {
var bitField = this._bitField;
var len = (bitField & 65535);
if (len > 0) {
if (((bitField & 16842752) !== 0)) {
var reason = this._fulfillmentHandler0;
this._settlePromise0(this._rejectionHandler0, reason, bitField);
this._rejectPromises(len, reason);
} else {
var value = this._rejectionHandler0;
this._settlePromise0(this._fulfillmentHandler0, value, bitField);
this._fulfillPromises(len, value);
}
this._setLength(0);
}
this._clearCancellationData();
};
Promise.prototype._settledValue = function() {
var bitField = this._bitField;
if (((bitField & 33554432) !== 0)) {
return this._rejectionHandler0;
} else if (((bitField & 16777216) !== 0)) {
return this._fulfillmentHandler0;
}
};
function deferResolve(v) {this.promise._resolveCallback(v);}
function deferReject(v) {this.promise._rejectCallback(v, false);}
Promise.defer = Promise.pending = function() {
debug.deprecated("Promise.defer", "new Promise");
var promise = new Promise(INTERNAL);
return {
promise: promise,
resolve: deferResolve,
reject: deferReject
};
};
util.notEnumerableProp(Promise,
"_makeSelfResolutionError",
makeSelfResolutionError);
require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
debug);
require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
require("./cancel")(Promise, PromiseArray, apiRejection, debug);
require("./direct_resolve")(Promise);
require("./synchronous_inspection")(Promise);
require("./join")(
Promise, PromiseArray, tryConvertToPromise, INTERNAL, debug);
Promise.Promise = Promise;
Promise.version = "3.4.0";
require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./call_get.js')(Promise);
require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
require('./timers.js')(Promise, INTERNAL, debug);
require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
require('./nodeify.js')(Promise);
require('./promisify.js')(Promise, INTERNAL);
require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./settle.js')(Promise, PromiseArray, debug);
require('./some.js')(Promise, PromiseArray, apiRejection);
require('./filter.js')(Promise, INTERNAL);
require('./each.js')(Promise, INTERNAL);
require('./any.js')(Promise);
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);
function fillTypes(value) {
var p = new Promise(INTERNAL);
p._fulfillmentHandler0 = value;
p._rejectionHandler0 = value;
p._promise0 = value;
p._receiver0 = value;
}
// Complete slack tracking, opt out of field-type tracking and
// stabilize map
fillTypes({a: 1});
fillTypes({b: 2});
fillTypes({c: 3});
fillTypes(1);
fillTypes(function(){});
fillTypes(undefined);
fillTypes(false);
fillTypes(new Promise(INTERNAL));
debug.setBounds(Async.firstLineError, util.lastLineError);
return Promise;
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise,
apiRejection, Proxyable) {
var util = require("./util");
var isArray = util.isArray;
function toResolutionValue(val) {
switch(val) {
case -2: return [];
case -3: return {};
}
}
function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
if (values instanceof Promise) {
promise._propagateFrom(values, 3);
}
promise._setOnCancel(this);
this._values = values;
this._length = 0;
this._totalResolved = 0;
this._init(undefined, -2);
}
util.inherits(PromiseArray, Proxyable);
PromiseArray.prototype.length = function () {
return this._length;
};
PromiseArray.prototype.promise = function () {
return this._promise;
};
PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
var values = tryConvertToPromise(this._values, this._promise);
if (values instanceof Promise) {
values = values._target();
var bitField = values._bitField;
;
this._values = values;
if (((bitField & 50397184) === 0)) {
this._promise._setAsyncGuaranteed();
return values._then(
init,
this._reject,
undefined,
this,
resolveValueIfEmpty
);
} else if (((bitField & 33554432) !== 0)) {
values = values._value();
} else if (((bitField & 16777216) !== 0)) {
return this._reject(values._reason());
} else {
return this._cancel();
}
}
values = util.asArray(values);
if (values === null) {
var err = apiRejection(
"expecting an array or an iterable object but got " + util.classString(values)).reason();
this._promise._rejectCallback(err, false);
return;
}
if (values.length === 0) {
if (resolveValueIfEmpty === -5) {
this._resolveEmptyArray();
}
else {
this._resolve(toResolutionValue(resolveValueIfEmpty));
}
return;
}
this._iterate(values);
};
PromiseArray.prototype._iterate = function(values) {
var len = this.getActualLength(values.length);
this._length = len;
this._values = this.shouldCopyValues() ? new Array(len) : this._values;
var result = this._promise;
var isResolved = false;
var bitField = null;
for (var i = 0; i < len; ++i) {
var maybePromise = tryConvertToPromise(values[i], result);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
bitField = maybePromise._bitField;
} else {
bitField = null;
}
if (isResolved) {
if (bitField !== null) {
maybePromise.suppressUnhandledRejections();
}
} else if (bitField !== null) {
if (((bitField & 50397184) === 0)) {
maybePromise._proxy(this, i);
this._values[i] = maybePromise;
} else if (((bitField & 33554432) !== 0)) {
isResolved = this._promiseFulfilled(maybePromise._value(), i);
} else if (((bitField & 16777216) !== 0)) {
isResolved = this._promiseRejected(maybePromise._reason(), i);
} else {
isResolved = this._promiseCancelled(i);
}
} else {
isResolved = this._promiseFulfilled(maybePromise, i);
}
}
if (!isResolved) result._setAsyncGuaranteed();
};
PromiseArray.prototype._isResolved = function () {
return this._values === null;
};
PromiseArray.prototype._resolve = function (value) {
this._values = null;
this._promise._fulfill(value);
};
PromiseArray.prototype._cancel = function() {
if (this._isResolved() || !this._promise.isCancellable()) return;
this._values = null;
this._promise._cancel();
};
PromiseArray.prototype._reject = function (reason) {
this._values = null;
this._promise._rejectCallback(reason, false);
};
PromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
return true;
}
return false;
};
PromiseArray.prototype._promiseCancelled = function() {
this._cancel();
return true;
};
PromiseArray.prototype._promiseRejected = function (reason) {
this._totalResolved++;
this._reject(reason);
return true;
};
PromiseArray.prototype._resultCancelled = function() {
if (this._isResolved()) return;
var values = this._values;
this._cancel();
if (values instanceof Promise) {
values.cancel();
} else {
for (var i = 0; i < values.length; ++i) {
if (values[i] instanceof Promise) {
values[i].cancel();
}
}
}
};
PromiseArray.prototype.shouldCopyValues = function () {
return true;
};
PromiseArray.prototype.getActualLength = function (len) {
return len;
};
return PromiseArray;
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise, INTERNAL) {
var THIS = {};
var util = require("./util");
var nodebackForPromise = require("./nodeback");
var withAppended = util.withAppended;
var maybeWrapAsError = util.maybeWrapAsError;
var canEvaluate = util.canEvaluate;
var TypeError = require("./errors").TypeError;
var defaultSuffix = "Async";
var defaultPromisified = {__isPromisified__: true};
var noCopyProps = [
"arity", "length",
"name",
"arguments",
"caller",
"callee",
"prototype",
"__isPromisified__"
];
var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
var defaultFilter = function(name) {
return util.isIdentifier(name) &&
name.charAt(0) !== "_" &&
name !== "constructor";
};
function propsFilter(key) {
return !noCopyPropsPattern.test(key);
}
function isPromisified(fn) {
try {
return fn.__isPromisified__ === true;
}
catch (e) {
return false;
}
}
function hasPromisified(obj, key, suffix) {
var val = util.getDataPropertyOrDefault(obj, key + suffix,
defaultPromisified);
return val ? isPromisified(val) : false;
}
function checkValid(ret, suffix, suffixRegexp) {
for (var i = 0; i < ret.length; i += 2) {
var key = ret[i];
if (suffixRegexp.test(key)) {
var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
for (var j = 0; j < ret.length; j += 2) {
if (ret[j] === keyWithoutAsyncSuffix) {
throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
.replace("%s", suffix));
}
}
}
}
}
function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
var keys = util.inheritedDataKeys(obj);
var ret = [];
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var value = obj[key];
var passesDefaultFilter = filter === defaultFilter
? true : defaultFilter(key, value, obj);
if (typeof value === "function" &&
!isPromisified(value) &&
!hasPromisified(obj, key, suffix) &&
filter(key, value, obj, passesDefaultFilter)) {
ret.push(key, value);
}
}
checkValid(ret, suffix, suffixRegexp);
return ret;
}
var escapeIdentRegex = function(str) {
return str.replace(/([$])/, "\\$");
};
var makeNodePromisifiedEval;
Eif (!false) {
var switchCaseArgumentOrder = function(likelyArgumentCount) {
var ret = [likelyArgumentCount];
var min = Math.max(0, likelyArgumentCount - 1 - 3);
for(var i = likelyArgumentCount - 1; i >= min; --i) {
ret.push(i);
}
for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
ret.push(i);
}
return ret;
};
var argumentSequence = function(argumentCount) {
return util.filledRange(argumentCount, "_arg", "");
};
var parameterDeclaration = function(parameterCount) {
return util.filledRange(
Math.max(parameterCount, 3), "_arg", "");
};
var parameterCount = function(fn) {
if (typeof fn.length === "number") {
return Math.max(Math.min(fn.length, 1023 + 1), 0);
}
return 0;
};
makeNodePromisifiedEval =
function(callback, receiver, originalName, fn, _, multiArgs) {
var newParameterCount = Math.max(0, parameterCount(fn) - 1);
var argumentOrder = switchCaseArgumentOrder(newParameterCount);
var shouldProxyThis = typeof callback === "string" || receiver === THIS;
function generateCallForArgumentCount(count) {
var args = argumentSequence(count).join(", ");
var comma = count > 0 ? ", " : "";
var ret;
if (shouldProxyThis) {
ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
} else {
ret = receiver === undefined
? "ret = callback({{args}}, nodeback); break;\n"
: "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
}
return ret.replace("{{args}}", args).replace(", ", comma);
}
function generateArgumentSwitchCase() {
var ret = "";
for (var i = 0; i < argumentOrder.length; ++i) {
ret += "case " + argumentOrder[i] +":" +
generateCallForArgumentCount(argumentOrder[i]);
}
ret += " \n\
default: \n\
var args = new Array(len + 1); \n\
var i = 0; \n\
for (var i = 0; i < len; ++i) { \n\
args[i] = arguments[i]; \n\
} \n\
args[i] = nodeback; \n\
[CodeForCall] \n\
break; \n\
".replace("[CodeForCall]", (shouldProxyThis
? "ret = callback.apply(this, args);\n"
: "ret = callback.apply(receiver, args);\n"));
return ret;
}
var getFunctionCode = typeof callback === "string"
? ("this != null ? this['"+callback+"'] : fn")
: "fn";
var body = "'use strict'; \n\
var ret = function (Parameters) { \n\
'use strict'; \n\
var len = arguments.length; \n\
var promise = new Promise(INTERNAL); \n\
promise._captureStackTrace(); \n\
var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
var ret; \n\
var callback = tryCatch([GetFunctionCode]); \n\
switch(len) { \n\
[CodeForSwitchCase] \n\
} \n\
if (ret === errorObj) { \n\
promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
} \n\
if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
return promise; \n\
}; \n\
notEnumerableProp(ret, '__isPromisified__', true); \n\
return ret; \n\
".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
.replace("[GetFunctionCode]", getFunctionCode);
body = body.replace("Parameters", parameterDeclaration(newParameterCount));
return new Function("Promise",
"fn",
"receiver",
"withAppended",
"maybeWrapAsError",
"nodebackForPromise",
"tryCatch",
"errorObj",
"notEnumerableProp",
"INTERNAL",
body)(
Promise,
fn,
receiver,
withAppended,
maybeWrapAsError,
nodebackForPromise,
util.tryCatch,
util.errorObj,
util.notEnumerableProp,
INTERNAL);
};
}
function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
var defaultThis = (function() {return this;})();
var method = callback;
if (typeof method === "string") {
callback = fn;
}
function promisified() {
var _receiver = receiver;
if (receiver === THIS) _receiver = this;
var promise = new Promise(INTERNAL);
promise._captureStackTrace();
var cb = typeof method === "string" && this !== defaultThis
? this[method] : callback;
var fn = nodebackForPromise(promise, multiArgs);
try {
cb.apply(_receiver, withAppended(arguments, fn));
} catch(e) {
promise._rejectCallback(maybeWrapAsError(e), true, true);
}
if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
return promise;
}
util.notEnumerableProp(promisified, "__isPromisified__", true);
return promisified;
}
var makeNodePromisified = canEvaluate
? makeNodePromisifiedEval
: makeNodePromisifiedClosure;
function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
var methods =
promisifiableMethods(obj, suffix, suffixRegexp, filter);
for (var i = 0, len = methods.length; i < len; i+= 2) {
var key = methods[i];
var fn = methods[i+1];
var promisifiedKey = key + suffix;
if (promisifier === makeNodePromisified) {
obj[promisifiedKey] =
makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
} else {
var promisified = promisifier(fn, function() {
return makeNodePromisified(key, THIS, key,
fn, suffix, multiArgs);
});
util.notEnumerableProp(promisified, "__isPromisified__", true);
obj[promisifiedKey] = promisified;
}
}
util.toFastProperties(obj);
return obj;
}
function promisify(callback, receiver, multiArgs) {
return makeNodePromisified(callback, receiver, undefined,
callback, null, multiArgs);
}
Promise.promisify = function (fn, options) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
if (isPromisified(fn)) {
return fn;
}
options = Object(options);
var receiver = options.context === undefined ? THIS : options.context;
var multiArgs = !!options.multiArgs;
var ret = promisify(fn, receiver, multiArgs);
util.copyDescriptors(fn, ret, propsFilter);
return ret;
};
Promise.promisifyAll = function (target, options) {
if (typeof target !== "function" && typeof target !== "object") {
throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
options = Object(options);
var multiArgs = !!options.multiArgs;
var suffix = options.suffix;
if (typeof suffix !== "string") suffix = defaultSuffix;
var filter = options.filter;
if (typeof filter !== "function") filter = defaultFilter;
var promisifier = options.promisifier;
if (typeof promisifier !== "function") promisifier = makeNodePromisified;
if (!util.isIdentifier(suffix)) {
throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var keys = util.inheritedDataKeys(target);
for (var i = 0; i < keys.length; ++i) {
var value = target[keys[i]];
if (keys[i] !== "constructor" &&
util.isClass(value)) {
promisifyAll(value.prototype, suffix, filter, promisifier,
multiArgs);
promisifyAll(value, suffix, filter, promisifier, multiArgs);
}
}
return promisifyAll(target, suffix, filter, promisifier, multiArgs);
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(
Promise, PromiseArray, tryConvertToPromise, apiRejection) {
var util = require("./util");
var isObject = util.isObject;
var es5 = require("./es5");
var Es6Map;
Eif (typeof Map === "function") Es6Map = Map;
var mapToEntries = (function() {
var index = 0;
var size = 0;
function extractEntry(value, key) {
this[index] = value;
this[index + size] = key;
index++;
}
return function mapToEntries(map) {
size = map.size;
index = 0;
var ret = new Array(map.size * 2);
map.forEach(extractEntry, ret);
return ret;
};
})();
var entriesToMap = function(entries) {
var ret = new Es6Map();
var length = entries.length / 2 | 0;
for (var i = 0; i < length; ++i) {
var key = entries[length + i];
var value = entries[i];
ret.set(key, value);
}
return ret;
};
function PropertiesPromiseArray(obj) {
var isMap = false;
var entries;
if (Es6Map !== undefined && obj instanceof Es6Map) {
entries = mapToEntries(obj);
isMap = true;
} else {
var keys = es5.keys(obj);
var len = keys.length;
entries = new Array(len * 2);
for (var i = 0; i < len; ++i) {
var key = keys[i];
entries[i] = obj[key];
entries[i + len] = key;
}
}
this.constructor$(entries);
this._isMap = isMap;
this._init$(undefined, -3);
}
util.inherits(PropertiesPromiseArray, PromiseArray);
PropertiesPromiseArray.prototype._init = function () {};
PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
var val;
if (this._isMap) {
val = entriesToMap(this._values);
} else {
val = {};
var keyOffset = this.length();
for (var i = 0, len = this.length(); i < len; ++i) {
val[this._values[i + keyOffset]] = this._values[i];
}
}
this._resolve(val);
return true;
}
return false;
};
PropertiesPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
PropertiesPromiseArray.prototype.getActualLength = function (len) {
return len >> 1;
};
function props(promises) {
var ret;
var castValue = tryConvertToPromise(promises);
if (!isObject(castValue)) {
return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
} else if (castValue instanceof Promise) {
ret = castValue._then(
Promise.props, undefined, undefined, undefined, undefined);
} else {
ret = new PropertiesPromiseArray(castValue).promise();
}
if (castValue instanceof Promise) {
ret._propagateFrom(castValue, 2);
}
return ret;
}
Promise.prototype.props = function () {
return props(this);
};
Promise.props = function (promises) {
return props(promises);
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | 1 1 2 2 2 1 1 1 1 1 1 1 1 1 1 | "use strict"; function arrayMove(src, srcIndex, dst, dstIndex, len) { for (var j = 0; j < len; ++j) { dst[j + dstIndex] = src[j + srcIndex]; src[j + srcIndex] = void 0; } } function Queue(capacity) { this._capacity = capacity; this._length = 0; this._front = 0; } Queue.prototype._willBeOverCapacity = function (size) { return this._capacity < size; }; Queue.prototype._pushOne = function (arg) { var length = this.length(); this._checkCapacity(length + 1); var i = (this._front + length) & (this._capacity - 1); this[i] = arg; this._length = length + 1; }; Queue.prototype._unshiftOne = function(value) { var capacity = this._capacity; this._checkCapacity(this.length() + 1); var front = this._front; var i = (((( front - 1 ) & ( capacity - 1) ) ^ capacity ) - capacity ); this[i] = value; this._front = i; this._length = this.length() + 1; }; Queue.prototype.unshift = function(fn, receiver, arg) { this._unshiftOne(arg); this._unshiftOne(receiver); this._unshiftOne(fn); }; Queue.prototype.push = function (fn, receiver, arg) { var length = this.length() + 3; if (this._willBeOverCapacity(length)) { this._pushOne(fn); this._pushOne(receiver); this._pushOne(arg); return; } var j = this._front + length - 3; this._checkCapacity(length); var wrapMask = this._capacity - 1; this[(j + 0) & wrapMask] = fn; this[(j + 1) & wrapMask] = receiver; this[(j + 2) & wrapMask] = arg; this._length = length; }; Queue.prototype.shift = function () { var front = this._front, ret = this[front]; this[front] = undefined; this._front = (front + 1) & (this._capacity - 1); this._length--; return ret; }; Queue.prototype.length = function () { return this._length; }; Queue.prototype._checkCapacity = function (size) { if (this._capacity < size) { this._resizeTo(this._capacity << 1); } }; Queue.prototype._resizeTo = function (capacity) { var oldCapacity = this._capacity; this._capacity = capacity; var front = this._front; var length = this._length; var moveItemsCount = (front + length) & (oldCapacity - 1); arrayMove(this, 0, this, oldCapacity, moveItemsCount); }; module.exports = Queue; |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 1 1 1 1 1 1 | "use strict";
module.exports = function(
Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var util = require("./util");
var raceLater = function (promise) {
return promise.then(function(array) {
return race(array, promise);
});
};
function race(promises, parent) {
var maybePromise = tryConvertToPromise(promises);
if (maybePromise instanceof Promise) {
return raceLater(maybePromise);
} else {
promises = util.asArray(promises);
if (promises === null)
return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
}
var ret = new Promise(INTERNAL);
if (parent !== undefined) {
ret._propagateFrom(parent, 3);
}
var fulfill = ret._fulfill;
var reject = ret._reject;
for (var i = 0, len = promises.length; i < len; ++i) {
var val = promises[i];
if (val === undefined && !(i in promises)) {
continue;
}
Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
}
return ret;
}
Promise.race = function (promises) {
return race(promises, undefined);
};
Promise.prototype.race = function () {
return race(this, undefined);
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL,
debug) {
var getDomain = Promise._getDomain;
var util = require("./util");
var tryCatch = util.tryCatch;
function ReductionPromiseArray(promises, fn, initialValue, _each) {
this.constructor$(promises);
var domain = getDomain();
this._fn = domain === null ? fn : domain.bind(fn);
if (initialValue !== undefined) {
initialValue = Promise.resolve(initialValue);
initialValue._attachCancellationCallback(this);
}
this._initialValue = initialValue;
this._currentCancellable = null;
this._eachValues = _each === INTERNAL ? [] : undefined;
this._promise._captureStackTrace();
this._init$(undefined, -5);
}
util.inherits(ReductionPromiseArray, PromiseArray);
ReductionPromiseArray.prototype._gotAccum = function(accum) {
if (this._eachValues !== undefined && accum !== INTERNAL) {
this._eachValues.push(accum);
}
};
ReductionPromiseArray.prototype._eachComplete = function(value) {
this._eachValues.push(value);
return this._eachValues;
};
ReductionPromiseArray.prototype._init = function() {};
ReductionPromiseArray.prototype._resolveEmptyArray = function() {
this._resolve(this._eachValues !== undefined ? this._eachValues
: this._initialValue);
};
ReductionPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
ReductionPromiseArray.prototype._resolve = function(value) {
this._promise._resolveCallback(value);
this._values = null;
};
ReductionPromiseArray.prototype._resultCancelled = function(sender) {
if (sender === this._initialValue) return this._cancel();
if (this._isResolved()) return;
this._resultCancelled$();
if (this._currentCancellable instanceof Promise) {
this._currentCancellable.cancel();
}
if (this._initialValue instanceof Promise) {
this._initialValue.cancel();
}
};
ReductionPromiseArray.prototype._iterate = function (values) {
this._values = values;
var value;
var i;
var length = values.length;
if (this._initialValue !== undefined) {
value = this._initialValue;
i = 0;
} else {
value = Promise.resolve(values[0]);
i = 1;
}
this._currentCancellable = value;
if (!value.isRejected()) {
for (; i < length; ++i) {
var ctx = {
accum: null,
value: values[i],
index: i,
length: length,
array: this
};
value = value._then(gotAccum, undefined, undefined, ctx, undefined);
}
}
if (this._eachValues !== undefined) {
value = value
._then(this._eachComplete, undefined, undefined, this, undefined);
}
value._then(completed, completed, undefined, value, this);
};
Promise.prototype.reduce = function (fn, initialValue) {
return reduce(this, fn, initialValue, null);
};
Promise.reduce = function (promises, fn, initialValue, _each) {
return reduce(promises, fn, initialValue, _each);
};
function completed(valueOrReason, array) {
if (this.isFulfilled()) {
array._resolve(valueOrReason);
} else {
array._reject(valueOrReason);
}
}
function reduce(promises, fn, initialValue, _each) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
return array.promise();
}
function gotAccum(accum) {
this.accum = accum;
this.array._gotAccum(accum);
var value = tryConvertToPromise(this.value, this.array._promise);
if (value instanceof Promise) {
this.array._currentCancellable = value;
return value._then(gotValue, undefined, undefined, this, undefined);
} else {
return gotValue.call(this, value);
}
}
function gotValue(value) {
var array = this.array;
var promise = array._promise;
var fn = tryCatch(array._fn);
promise._pushContext();
var ret;
if (array._eachValues !== undefined) {
ret = fn.call(promise._boundValue(), value, this.index, this.length);
} else {
ret = fn.call(promise._boundValue(),
this.accum, value, this.index, this.length);
}
if (ret instanceof Promise) {
array._currentCancellable = ret;
}
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret,
promiseCreated,
array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
promise
);
return ret;
}
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | 1 1 1 1 1 1 1 1 1 | "use strict";
var util = require("./util");
var schedule;
var noAsyncScheduler = function() {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
};
var NativePromise = util.getNativePromise();
Eif (util.isNode && typeof MutationObserver === "undefined") {
var GlobalSetImmediate = global.setImmediate;
var ProcessNextTick = process.nextTick;
schedule = util.isRecentNode
? function(fn) { GlobalSetImmediate.call(global, fn); }
: function(fn) { ProcessNextTick.call(process, fn); };
} else if (typeof NativePromise === "function") {
var nativePromise = NativePromise.resolve();
schedule = function(fn) {
nativePromise.then(fn);
};
} else if ((typeof MutationObserver !== "undefined") &&
!(typeof window !== "undefined" &&
window.navigator &&
window.navigator.standalone)) {
schedule = (function() {
var div = document.createElement("div");
var opts = {attributes: true};
var toggleScheduled = false;
var div2 = document.createElement("div");
var o2 = new MutationObserver(function() {
div.classList.toggle("foo");
toggleScheduled = false;
});
o2.observe(div2, opts);
var scheduleToggle = function() {
if (toggleScheduled) return;
toggleScheduled = true;
div2.classList.toggle("foo");
};
return function schedule(fn) {
var o = new MutationObserver(function() {
o.disconnect();
fn();
});
o.observe(div, opts);
scheduleToggle();
};
})();
} else if (typeof setImmediate !== "undefined") {
schedule = function (fn) {
setImmediate(fn);
};
} else if (typeof setTimeout !== "undefined") {
schedule = function (fn) {
setTimeout(fn, 0);
};
} else {
schedule = noAsyncScheduler;
}
module.exports = schedule;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports =
function(Promise, PromiseArray, debug) {
var PromiseInspection = Promise.PromiseInspection;
var util = require("./util");
function SettledPromiseArray(values) {
this.constructor$(values);
}
util.inherits(SettledPromiseArray, PromiseArray);
SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
this._values[index] = inspection;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
return true;
}
return false;
};
SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
var ret = new PromiseInspection();
ret._bitField = 33554432;
ret._settledValueField = value;
return this._promiseResolved(index, ret);
};
SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
var ret = new PromiseInspection();
ret._bitField = 16777216;
ret._settledValueField = reason;
return this._promiseResolved(index, ret);
};
Promise.settle = function (promises) {
debug.deprecated(".settle()", ".reflect()");
return new SettledPromiseArray(promises).promise();
};
Promise.prototype.settle = function () {
return Promise.settle(this);
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports =
function(Promise, PromiseArray, apiRejection) {
var util = require("./util");
var RangeError = require("./errors").RangeError;
var AggregateError = require("./errors").AggregateError;
var isArray = util.isArray;
var CANCELLATION = {};
function SomePromiseArray(values) {
this.constructor$(values);
this._howMany = 0;
this._unwrap = false;
this._initialized = false;
}
util.inherits(SomePromiseArray, PromiseArray);
SomePromiseArray.prototype._init = function () {
if (!this._initialized) {
return;
}
if (this._howMany === 0) {
this._resolve([]);
return;
}
this._init$(undefined, -5);
var isArrayResolved = isArray(this._values);
if (!this._isResolved() &&
isArrayResolved &&
this._howMany > this._canPossiblyFulfill()) {
this._reject(this._getRangeError(this.length()));
}
};
SomePromiseArray.prototype.init = function () {
this._initialized = true;
this._init();
};
SomePromiseArray.prototype.setUnwrap = function () {
this._unwrap = true;
};
SomePromiseArray.prototype.howMany = function () {
return this._howMany;
};
SomePromiseArray.prototype.setHowMany = function (count) {
this._howMany = count;
};
SomePromiseArray.prototype._promiseFulfilled = function (value) {
this._addFulfilled(value);
if (this._fulfilled() === this.howMany()) {
this._values.length = this.howMany();
if (this.howMany() === 1 && this._unwrap) {
this._resolve(this._values[0]);
} else {
this._resolve(this._values);
}
return true;
}
return false;
};
SomePromiseArray.prototype._promiseRejected = function (reason) {
this._addRejected(reason);
return this._checkOutcome();
};
SomePromiseArray.prototype._promiseCancelled = function () {
if (this._values instanceof Promise || this._values == null) {
return this._cancel();
}
this._addRejected(CANCELLATION);
return this._checkOutcome();
};
SomePromiseArray.prototype._checkOutcome = function() {
if (this.howMany() > this._canPossiblyFulfill()) {
var e = new AggregateError();
for (var i = this.length(); i < this._values.length; ++i) {
if (this._values[i] !== CANCELLATION) {
e.push(this._values[i]);
}
}
if (e.length > 0) {
this._reject(e);
} else {
this._cancel();
}
return true;
}
return false;
};
SomePromiseArray.prototype._fulfilled = function () {
return this._totalResolved;
};
SomePromiseArray.prototype._rejected = function () {
return this._values.length - this.length();
};
SomePromiseArray.prototype._addRejected = function (reason) {
this._values.push(reason);
};
SomePromiseArray.prototype._addFulfilled = function (value) {
this._values[this._totalResolved++] = value;
};
SomePromiseArray.prototype._canPossiblyFulfill = function () {
return this.length() - this._rejected();
};
SomePromiseArray.prototype._getRangeError = function (count) {
var message = "Input array must contain at least " +
this._howMany + " items but contains only " + count + " items";
return new RangeError(message);
};
SomePromiseArray.prototype._resolveEmptyArray = function () {
this._reject(this._getRangeError(0));
};
function some(promises, howMany) {
if ((howMany | 0) !== howMany || howMany < 0) {
return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(howMany);
ret.init();
return promise;
}
Promise.some = function (promises, howMany) {
return some(promises, howMany);
};
Promise.prototype.some = function (howMany) {
return some(this, howMany);
};
Promise._SomePromiseArray = SomePromiseArray;
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise) {
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValueField = promise._isFateSealed()
? promise._settledValue() : undefined;
}
else {
this._bitField = 0;
this._settledValueField = undefined;
}
}
PromiseInspection.prototype._settledValue = function() {
return this._settledValueField;
};
var value = PromiseInspection.prototype.value = function () {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var reason = PromiseInspection.prototype.error =
PromiseInspection.prototype.reason = function () {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
return (this._bitField & 33554432) !== 0;
};
var isRejected = PromiseInspection.prototype.isRejected = function () {
return (this._bitField & 16777216) !== 0;
};
var isPending = PromiseInspection.prototype.isPending = function () {
return (this._bitField & 50397184) === 0;
};
var isResolved = PromiseInspection.prototype.isResolved = function () {
return (this._bitField & 50331648) !== 0;
};
PromiseInspection.prototype.isCancelled =
Promise.prototype._isCancelled = function() {
return (this._bitField & 65536) === 65536;
};
Promise.prototype.isCancelled = function() {
return this._target()._isCancelled();
};
Promise.prototype.isPending = function() {
return isPending.call(this._target());
};
Promise.prototype.isRejected = function() {
return isRejected.call(this._target());
};
Promise.prototype.isFulfilled = function() {
return isFulfilled.call(this._target());
};
Promise.prototype.isResolved = function() {
return isResolved.call(this._target());
};
Promise.prototype.value = function() {
return value.call(this._target());
};
Promise.prototype.reason = function() {
var target = this._target();
target._unsetRejectionIsUnhandled();
return reason.call(target);
};
Promise.prototype._value = function() {
return this._settledValue();
};
Promise.prototype._reason = function() {
this._unsetRejectionIsUnhandled();
return this._settledValue();
};
Promise.PromiseInspection = PromiseInspection;
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise, INTERNAL) {
var util = require("./util");
var errorObj = util.errorObj;
var isObject = util.isObject;
function tryConvertToPromise(obj, context) {
if (isObject(obj)) {
if (obj instanceof Promise) return obj;
var then = getThen(obj);
if (then === errorObj) {
if (context) context._pushContext();
var ret = Promise.reject(then.e);
if (context) context._popContext();
return ret;
} else if (typeof then === "function") {
if (isAnyBluebirdPromise(obj)) {
var ret = new Promise(INTERNAL);
obj._then(
ret._fulfill,
ret._reject,
undefined,
ret,
null
);
return ret;
}
return doThenable(obj, then, context);
}
}
return obj;
}
function doGetThen(obj) {
return obj.then;
}
function getThen(obj) {
try {
return doGetThen(obj);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
try {
return hasProp.call(obj, "_promise0");
} catch (e) {
return false;
}
}
function doThenable(x, then, context) {
var promise = new Promise(INTERNAL);
var ret = promise;
if (context) context._pushContext();
promise._captureStackTrace();
if (context) context._popContext();
var synchronous = true;
var result = util.tryCatch(then).call(x, resolve, reject);
synchronous = false;
if (promise && result === errorObj) {
promise._rejectCallback(result.e, true, true);
promise = null;
}
function resolve(value) {
if (!promise) return;
promise._resolveCallback(value);
promise = null;
}
function reject(reason) {
if (!promise) return;
promise._rejectCallback(reason, synchronous, true);
promise = null;
}
return ret;
}
return tryConvertToPromise;
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function(Promise, INTERNAL, debug) {
var util = require("./util");
var TimeoutError = Promise.TimeoutError;
function HandleWrapper(handle) {
this.handle = handle;
}
HandleWrapper.prototype._resultCancelled = function() {
clearTimeout(this.handle);
};
var afterValue = function(value) { return delay(+this).thenReturn(value); };
var delay = Promise.delay = function (ms, value) {
var ret;
var handle;
if (value !== undefined) {
ret = Promise.resolve(value)
._then(afterValue, null, null, ms, undefined);
if (debug.cancellation() && value instanceof Promise) {
ret._setOnCancel(value);
}
} else {
ret = new Promise(INTERNAL);
handle = setTimeout(function() { ret._fulfill(); }, +ms);
if (debug.cancellation()) {
ret._setOnCancel(new HandleWrapper(handle));
}
}
ret._setAsyncGuaranteed();
return ret;
};
Promise.prototype.delay = function (ms) {
return delay(ms, this);
};
var afterTimeout = function (promise, message, parent) {
var err;
if (typeof message !== "string") {
if (message instanceof Error) {
err = message;
} else {
err = new TimeoutError("operation timed out");
}
} else {
err = new TimeoutError(message);
}
util.markAsOriginatingFromRejection(err);
promise._attachExtraTrace(err);
promise._reject(err);
if (parent != null) {
parent.cancel();
}
};
function successClear(value) {
clearTimeout(this.handle);
return value;
}
function failureClear(reason) {
clearTimeout(this.handle);
throw reason;
}
Promise.prototype.timeout = function (ms, message) {
ms = +ms;
var ret, parent;
var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
if (ret.isPending()) {
afterTimeout(ret, message, parent);
}
}, ms));
if (debug.cancellation()) {
parent = this.then();
ret = parent._then(successClear, failureClear,
undefined, handleWrapper, undefined);
ret._setOnCancel(handleWrapper);
} else {
ret = this._then(successClear, failureClear,
undefined, handleWrapper, undefined);
}
return ret;
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
module.exports = function (Promise, apiRejection, tryConvertToPromise,
createContext, INTERNAL, debug) {
var util = require("./util");
var TypeError = require("./errors").TypeError;
var inherits = require("./util").inherits;
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var NULL = {};
function thrower(e) {
setTimeout(function(){throw e;}, 0);
}
function castPreservingDisposable(thenable) {
var maybePromise = tryConvertToPromise(thenable);
if (maybePromise !== thenable &&
typeof thenable._isDisposable === "function" &&
typeof thenable._getDisposer === "function" &&
thenable._isDisposable()) {
maybePromise._setDisposable(thenable._getDisposer());
}
return maybePromise;
}
function dispose(resources, inspection) {
var i = 0;
var len = resources.length;
var ret = new Promise(INTERNAL);
function iterator() {
if (i >= len) return ret._fulfill();
var maybePromise = castPreservingDisposable(resources[i++]);
if (maybePromise instanceof Promise &&
maybePromise._isDisposable()) {
try {
maybePromise = tryConvertToPromise(
maybePromise._getDisposer().tryDispose(inspection),
resources.promise);
} catch (e) {
return thrower(e);
}
if (maybePromise instanceof Promise) {
return maybePromise._then(iterator, thrower,
null, null, null);
}
}
iterator();
}
iterator();
return ret;
}
function Disposer(data, promise, context) {
this._data = data;
this._promise = promise;
this._context = context;
}
Disposer.prototype.data = function () {
return this._data;
};
Disposer.prototype.promise = function () {
return this._promise;
};
Disposer.prototype.resource = function () {
if (this.promise().isFulfilled()) {
return this.promise().value();
}
return NULL;
};
Disposer.prototype.tryDispose = function(inspection) {
var resource = this.resource();
var context = this._context;
if (context !== undefined) context._pushContext();
var ret = resource !== NULL
? this.doDispose(resource, inspection) : null;
if (context !== undefined) context._popContext();
this._promise._unsetDisposable();
this._data = null;
return ret;
};
Disposer.isDisposer = function (d) {
return (d != null &&
typeof d.resource === "function" &&
typeof d.tryDispose === "function");
};
function FunctionDisposer(fn, promise, context) {
this.constructor$(fn, promise, context);
}
inherits(FunctionDisposer, Disposer);
FunctionDisposer.prototype.doDispose = function (resource, inspection) {
var fn = this.data();
return fn.call(resource, resource, inspection);
};
function maybeUnwrapDisposer(value) {
if (Disposer.isDisposer(value)) {
this.resources[this.index]._setDisposable(value);
return value.promise();
}
return value;
}
function ResourceList(length) {
this.length = length;
this.promise = null;
this[length-1] = null;
}
ResourceList.prototype._resultCancelled = function() {
var len = this.length;
for (var i = 0; i < len; ++i) {
var item = this[i];
if (item instanceof Promise) {
item.cancel();
}
}
};
Promise.using = function () {
var len = arguments.length;
if (len < 2) return apiRejection(
"you must pass at least 2 arguments to Promise.using");
var fn = arguments[len - 1];
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var input;
var spreadArgs = true;
if (len === 2 && Array.isArray(arguments[0])) {
input = arguments[0];
len = input.length;
spreadArgs = false;
} else {
input = arguments;
len--;
}
var resources = new ResourceList(len);
for (var i = 0; i < len; ++i) {
var resource = input[i];
if (Disposer.isDisposer(resource)) {
var disposer = resource;
resource = resource.promise();
resource._setDisposable(disposer);
} else {
var maybePromise = tryConvertToPromise(resource);
if (maybePromise instanceof Promise) {
resource =
maybePromise._then(maybeUnwrapDisposer, null, null, {
resources: resources,
index: i
}, undefined);
}
}
resources[i] = resource;
}
var reflectedResources = new Array(resources.length);
for (var i = 0; i < reflectedResources.length; ++i) {
reflectedResources[i] = Promise.resolve(resources[i]).reflect();
}
var resultPromise = Promise.all(reflectedResources)
.then(function(inspections) {
for (var i = 0; i < inspections.length; ++i) {
var inspection = inspections[i];
if (inspection.isRejected()) {
errorObj.e = inspection.error();
return errorObj;
} else if (!inspection.isFulfilled()) {
resultPromise.cancel();
return;
}
inspections[i] = inspection.value();
}
promise._pushContext();
fn = tryCatch(fn);
var ret = spreadArgs
? fn.apply(undefined, inspections) : fn(inspections);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret, promiseCreated, "Promise.using", promise);
return ret;
});
var promise = resultPromise.lastly(function() {
var inspection = new Promise.PromiseInspection(resultPromise);
return dispose(resources, inspection);
});
resources.promise = promise;
promise._setOnCancel(resources);
return promise;
};
Promise.prototype._setDisposable = function (disposer) {
this._bitField = this._bitField | 131072;
this._disposer = disposer;
};
Promise.prototype._isDisposable = function () {
return (this._bitField & 131072) > 0;
};
Promise.prototype._getDisposer = function () {
return this._disposer;
};
Promise.prototype._unsetDisposable = function () {
this._bitField = this._bitField & (~131072);
this._disposer = undefined;
};
Promise.prototype.disposer = function (fn) {
if (typeof fn === "function") {
return new FunctionDisposer(fn, this, createContext());
}
throw new TypeError();
};
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | 1 1 1 1 1 1 1 1 14 1 14 14 14 84 79 14 14 14 1 2 1 1 1 1 1 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 3 3 24 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 9 1 1 1 1 1 1 1 1 1 1 1 1 1 | "use strict";
var es5 = require("./es5");
var canEvaluate = typeof navigator == "undefined";
var errorObj = {e: {}};
var tryCatchTarget;
var globalObject = typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
typeof global !== "undefined" ? global :
this !== undefined ? this : null;
function tryCatcher() {
try {
var target = tryCatchTarget;
tryCatchTarget = null;
return target.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
tryCatchTarget = fn;
return tryCatcher;
}
var inherits = function(Child, Parent) {
var hasProp = {}.hasOwnProperty;
function T() {
this.constructor = Child;
this.constructor$ = Parent;
for (var propertyName in Parent.prototype) {
if (hasProp.call(Parent.prototype, propertyName) &&
propertyName.charAt(propertyName.length-1) !== "$"
) {
this[propertyName + "$"] = Parent.prototype[propertyName];
}
}
}
T.prototype = Parent.prototype;
Child.prototype = new T();
return Child.prototype;
};
function isPrimitive(val) {
return val == null || val === true || val === false ||
typeof val === "string" || typeof val === "number";
}
function isObject(value) {
return typeof value === "function" ||
typeof value === "object" && value !== null;
}
function maybeWrapAsError(maybeError) {
if (!isPrimitive(maybeError)) return maybeError;
return new Error(safeToString(maybeError));
}
function withAppended(target, appendee) {
var len = target.length;
var ret = new Array(len + 1);
var i;
for (i = 0; i < len; ++i) {
ret[i] = target[i];
}
ret[i] = appendee;
return ret;
}
function getDataPropertyOrDefault(obj, key, defaultValue) {
if (es5.isES5) {
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null) {
return desc.get == null && desc.set == null
? desc.value
: defaultValue;
}
} else {
return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
}
}
function notEnumerableProp(obj, name, value) {
Iif (isPrimitive(obj)) return obj;
var descriptor = {
value: value,
configurable: true,
enumerable: false,
writable: true
};
es5.defineProperty(obj, name, descriptor);
return obj;
}
function thrower(r) {
throw r;
}
var inheritedDataKeys = (function() {
var excludedPrototypes = [
Array.prototype,
Object.prototype,
Function.prototype
];
var isExcludedProto = function(val) {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (excludedPrototypes[i] === val) {
return true;
}
}
return false;
};
Eif (es5.isES5) {
var getKeys = Object.getOwnPropertyNames;
return function(obj) {
var ret = [];
var visitedKeys = Object.create(null);
while (obj != null && !isExcludedProto(obj)) {
var keys;
try {
keys = getKeys(obj);
} catch (e) {
return ret;
}
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (visitedKeys[key]) continue;
visitedKeys[key] = true;
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null && desc.get == null && desc.set == null) {
ret.push(key);
}
}
obj = es5.getPrototypeOf(obj);
}
return ret;
};
} else {
var hasProp = {}.hasOwnProperty;
return function(obj) {
if (isExcludedProto(obj)) return [];
var ret = [];
/*jshint forin:false */
enumeration: for (var key in obj) {
if (hasProp.call(obj, key)) {
ret.push(key);
} else {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (hasProp.call(excludedPrototypes[i], key)) {
continue enumeration;
}
}
ret.push(key);
}
}
return ret;
};
}
})();
var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
function isClass(fn) {
try {
if (typeof fn === "function") {
var keys = es5.names(fn.prototype);
var hasMethods = es5.isES5 && keys.length > 1;
var hasMethodsOtherThanConstructor = keys.length > 0 &&
!(keys.length === 1 && keys[0] === "constructor");
var hasThisAssignmentAndStaticMethods =
thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
if (hasMethods || hasMethodsOtherThanConstructor ||
hasThisAssignmentAndStaticMethods) {
return true;
}
}
return false;
} catch (e) {
return false;
}
}
function toFastProperties(obj) {
/*jshint -W027,-W055,-W031*/
function FakeConstructor() {}
FakeConstructor.prototype = obj;
var l = 8;
while (l--) new FakeConstructor();
return obj;
eval(obj);
}
var rident = /^[a-z$_][a-z$_0-9]*$/i;
function isIdentifier(str) {
return rident.test(str);
}
function filledRange(count, prefix, suffix) {
var ret = new Array(count);
for(var i = 0; i < count; ++i) {
ret[i] = prefix + i + suffix;
}
return ret;
}
function safeToString(obj) {
try {
return obj + "";
} catch (e) {
return "[no string representation]";
}
}
function isError(obj) {
return obj !== null &&
typeof obj === "object" &&
typeof obj.message === "string" &&
typeof obj.name === "string";
}
function markAsOriginatingFromRejection(e) {
try {
notEnumerableProp(e, "isOperational", true);
}
catch(ignore) {}
}
function originatesFromRejection(e) {
if (e == null) return false;
return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
e["isOperational"] === true);
}
function canAttachTrace(obj) {
return isError(obj) && es5.propertyIsWritable(obj, "stack");
}
var ensureErrorObject = (function() {
Iif (!("stack" in new Error())) {
return function(value) {
if (canAttachTrace(value)) return value;
try {throw new Error(safeToString(value));}
catch(err) {return err;}
};
} else {
return function(value) {
if (canAttachTrace(value)) return value;
return new Error(safeToString(value));
};
}
})();
function classString(obj) {
return {}.toString.call(obj);
}
function copyDescriptors(from, to, filter) {
var keys = es5.names(from);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (filter(key)) {
try {
es5.defineProperty(to, key, es5.getDescriptor(from, key));
} catch (ignore) {}
}
}
}
var asArray = function(v) {
if (es5.isArray(v)) {
return v;
}
return null;
};
Eif (typeof Symbol !== "undefined" && Symbol.iterator) {
var ArrayFrom = typeof Array.from === "function" ? function(v) {
return Array.from(v);
} : function(v) {
var ret = [];
var it = v[Symbol.iterator]();
var itResult;
while (!((itResult = it.next()).done)) {
ret.push(itResult.value);
}
return ret;
};
asArray = function(v) {
if (es5.isArray(v)) {
return v;
} else if (v != null && typeof v[Symbol.iterator] === "function") {
return ArrayFrom(v);
}
return null;
};
}
var isNode = typeof process !== "undefined" &&
classString(process).toLowerCase() === "[object process]";
function env(key, def) {
return isNode ? process.env[key] : def;
}
function getNativePromise() {
Eif (typeof Promise === "function") {
try {
var promise = new Promise(function(){});
Eif ({}.toString.call(promise) === "[object Promise]") {
return Promise;
}
} catch (e) {}
}
}
var ret = {
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
getDataPropertyOrDefault: getDataPropertyOrDefault,
thrower: thrower,
isArray: es5.isArray,
asArray: asArray,
notEnumerableProp: notEnumerableProp,
isPrimitive: isPrimitive,
isObject: isObject,
isError: isError,
canEvaluate: canEvaluate,
errorObj: errorObj,
tryCatch: tryCatch,
inherits: inherits,
withAppended: withAppended,
maybeWrapAsError: maybeWrapAsError,
toFastProperties: toFastProperties,
filledRange: filledRange,
toString: safeToString,
canAttachTrace: canAttachTrace,
ensureErrorObject: ensureErrorObject,
originatesFromRejection: originatesFromRejection,
markAsOriginatingFromRejection: markAsOriginatingFromRejection,
classString: classString,
copyDescriptors: copyDescriptors,
hasDevTools: typeof chrome !== "undefined" && chrome &&
typeof chrome.loadTimes === "function",
isNode: isNode,
env: env,
global: globalObject,
getNativePromise: getNativePromise
};
ret.isRecentNode = ret.isNode && (function() {
var version = process.versions.node.split(".").map(Number);
return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
})();
Eif (ret.isNode) ret.toFastProperties(process);
try {throw new Error(); } catch (e) {ret.lastLineError = e;}
module.exports = ret;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| index.js | 12.5% | (5 / 40) | 0% | (0 / 47) | 0% | (0 / 3) | 12.5% | (5 / 40) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | 1 1 1 1 1 | 'use strict'; var hasOwn = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var isArray = function isArray(arr) { if (typeof Array.isArray === 'function') { return Array.isArray(arr); } return toStr.call(arr) === '[object Array]'; }; var isPlainObject = function isPlainObject(obj) { if (!obj || toStr.call(obj) !== '[object Object]') { return false; } var hasOwnConstructor = hasOwn.call(obj, 'constructor'); var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); // Not own constructor property must be Object if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for (key in obj) {/**/} return typeof key === 'undefined' || hasOwn.call(obj, key); }; module.exports = function extend() { var options, name, src, copy, copyIsArray, clone, target = arguments[0], i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if (typeof target === 'boolean') { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } else if ((typeof target !== 'object' && typeof target !== 'function') || target == null) { target = {}; } for (; i < length; ++i) { options = arguments[i]; // Only deal with non-null/undefined values if (options != null) { // Extend the base object for (name in options) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target !== copy) { // Recurse if we're merging plain objects or arrays if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[name] = extend(deep, clone, copy); // Don't bring in undefined values } else if (typeof copy !== 'undefined') { target[name] = copy; } } } } } // Return the modified object return target; }; |
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| jmespath.js | 10.64% | (98 / 921) | 0.47% | (2 / 422) | 1.2% | (1 / 83) | 10.64% | (98 / 921) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | (function(exports) {
"use strict";
function isArray(obj) {
if (obj !== null) {
return Object.prototype.toString.call(obj) === "[object Array]";
} else {
return false;
}
}
function isObject(obj) {
if (obj !== null) {
return Object.prototype.toString.call(obj) === "[object Object]";
} else {
return false;
}
}
function strictDeepEqual(first, second) {
// Check the scalar case first.
if (first === second) {
return true;
}
// Check if they are the same type.
var firstType = Object.prototype.toString.call(first);
if (firstType !== Object.prototype.toString.call(second)) {
return false;
}
// We know that first and second have the same type so we can just check the
// first type from now on.
if (isArray(first) === true) {
// Short circuit if they're not the same length;
if (first.length !== second.length) {
return false;
}
for (var i = 0; i < first.length; i++) {
if (strictDeepEqual(first[i], second[i]) === false) {
return false;
}
}
return true;
}
if (isObject(first) === true) {
// An object is equal if it has the same key/value pairs.
var keysSeen = {};
for (var key in first) {
if (hasOwnProperty.call(first, key)) {
if (strictDeepEqual(first[key], second[key]) === false) {
return false;
}
keysSeen[key] = true;
}
}
// Now check that there aren't any keys in second that weren't
// in first.
for (var key2 in second) {
if (hasOwnProperty.call(second, key2)) {
if (keysSeen[key2] !== true) {
return false;
}
}
}
return true;
}
return false;
}
function isFalse(obj) {
// From the spec:
// A false value corresponds to the following values:
// Empty list
// Empty object
// Empty string
// False boolean
// null value
// First check the scalar values.
if (obj === "" || obj === false || obj === null) {
return true;
} else if (isArray(obj) && obj.length === 0) {
// Check for an empty array.
return true;
} else if (isObject(obj)) {
// Check for an empty object.
for (var key in obj) {
// If there are any keys, then
// the object is not empty so the object
// is not false.
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
} else {
return false;
}
}
function objValues(obj) {
var keys = Object.keys(obj);
var values = [];
for (var i = 0; i < keys.length; i++) {
values.push(obj[keys[i]]);
}
return values;
}
function merge(a, b) {
var merged = {};
for (var key in a) {
merged[key] = a[key];
}
for (var key2 in b) {
merged[key2] = b[key2];
}
return merged;
}
var trimLeft;
Eif (typeof String.prototype.trimLeft === "function") {
trimLeft = function(str) {
return str.trimLeft();
};
} else {
trimLeft = function(str) {
return str.match(/^\s*(.*)/)[1];
};
}
// Type constants used to define functions.
var TYPE_NUMBER = 0;
var TYPE_ANY = 1;
var TYPE_STRING = 2;
var TYPE_ARRAY = 3;
var TYPE_OBJECT = 4;
var TYPE_BOOLEAN = 5;
var TYPE_EXPREF = 6;
var TYPE_NULL = 7;
var TYPE_ARRAY_NUMBER = 8;
var TYPE_ARRAY_STRING = 9;
var TOK_EOF = "EOF";
var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier";
var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier";
var TOK_RBRACKET = "Rbracket";
var TOK_RPAREN = "Rparen";
var TOK_COMMA = "Comma";
var TOK_COLON = "Colon";
var TOK_RBRACE = "Rbrace";
var TOK_NUMBER = "Number";
var TOK_CURRENT = "Current";
var TOK_EXPREF = "Expref";
var TOK_PIPE = "Pipe";
var TOK_OR = "Or";
var TOK_AND = "And";
var TOK_EQ = "EQ";
var TOK_GT = "GT";
var TOK_LT = "LT";
var TOK_GTE = "GTE";
var TOK_LTE = "LTE";
var TOK_NE = "NE";
var TOK_FLATTEN = "Flatten";
var TOK_STAR = "Star";
var TOK_FILTER = "Filter";
var TOK_DOT = "Dot";
var TOK_NOT = "Not";
var TOK_LBRACE = "Lbrace";
var TOK_LBRACKET = "Lbracket";
var TOK_LPAREN= "Lparen";
var TOK_LITERAL= "Literal";
// The "&", "[", "<", ">" tokens
// are not in basicToken because
// there are two token variants
// ("&&", "[?", "<=", ">="). This is specially handled
// below.
var basicTokens = {
".": TOK_DOT,
"*": TOK_STAR,
",": TOK_COMMA,
":": TOK_COLON,
"{": TOK_LBRACE,
"}": TOK_RBRACE,
"]": TOK_RBRACKET,
"(": TOK_LPAREN,
")": TOK_RPAREN,
"@": TOK_CURRENT
};
var operatorStartToken = {
"<": true,
">": true,
"=": true,
"!": true
};
var skipChars = {
" ": true,
"\t": true,
"\n": true
};
function isAlpha(ch) {
return (ch >= "a" && ch <= "z") ||
(ch >= "A" && ch <= "Z") ||
ch === "_";
}
function isNum(ch) {
return (ch >= "0" && ch <= "9") ||
ch === "-";
}
function isAlphaNum(ch) {
return (ch >= "a" && ch <= "z") ||
(ch >= "A" && ch <= "Z") ||
(ch >= "0" && ch <= "9") ||
ch === "_";
}
function Lexer() {
}
Lexer.prototype = {
tokenize: function(stream) {
var tokens = [];
this._current = 0;
var start;
var identifier;
var token;
while (this._current < stream.length) {
if (isAlpha(stream[this._current])) {
start = this._current;
identifier = this._consumeUnquotedIdentifier(stream);
tokens.push({type: TOK_UNQUOTEDIDENTIFIER,
value: identifier,
start: start});
} else if (basicTokens[stream[this._current]] !== undefined) {
tokens.push({type: basicTokens[stream[this._current]],
value: stream[this._current],
start: this._current});
this._current++;
} else if (isNum(stream[this._current])) {
token = this._consumeNumber(stream);
tokens.push(token);
} else if (stream[this._current] === "[") {
// No need to increment this._current. This happens
// in _consumeLBracket
token = this._consumeLBracket(stream);
tokens.push(token);
} else if (stream[this._current] === "\"") {
start = this._current;
identifier = this._consumeQuotedIdentifier(stream);
tokens.push({type: TOK_QUOTEDIDENTIFIER,
value: identifier,
start: start});
} else if (stream[this._current] === "'") {
start = this._current;
identifier = this._consumeRawStringLiteral(stream);
tokens.push({type: TOK_LITERAL,
value: identifier,
start: start});
} else if (stream[this._current] === "`") {
start = this._current;
var literal = this._consumeLiteral(stream);
tokens.push({type: TOK_LITERAL,
value: literal,
start: start});
} else if (operatorStartToken[stream[this._current]] !== undefined) {
tokens.push(this._consumeOperator(stream));
} else if (skipChars[stream[this._current]] !== undefined) {
// Ignore whitespace.
this._current++;
} else if (stream[this._current] === "&") {
start = this._current;
this._current++;
if (stream[this._current] === "&") {
this._current++;
tokens.push({type: TOK_AND, value: "&&", start: start});
} else {
tokens.push({type: TOK_EXPREF, value: "&", start: start});
}
} else if (stream[this._current] === "|") {
start = this._current;
this._current++;
if (stream[this._current] === "|") {
this._current++;
tokens.push({type: TOK_OR, value: "||", start: start});
} else {
tokens.push({type: TOK_PIPE, value: "|", start: start});
}
} else {
var error = new Error("Unknown character:" + stream[this._current]);
error.name = "LexerError";
throw error;
}
}
return tokens;
},
_consumeUnquotedIdentifier: function(stream) {
var start = this._current;
this._current++;
while (this._current < stream.length && isAlphaNum(stream[this._current])) {
this._current++;
}
return stream.slice(start, this._current);
},
_consumeQuotedIdentifier: function(stream) {
var start = this._current;
this._current++;
var maxLength = stream.length;
while (stream[this._current] !== "\"" && this._current < maxLength) {
// You can escape a double quote and you can escape an escape.
var current = this._current;
if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
stream[current + 1] === "\"")) {
current += 2;
} else {
current++;
}
this._current = current;
}
this._current++;
return JSON.parse(stream.slice(start, this._current));
},
_consumeRawStringLiteral: function(stream) {
var start = this._current;
this._current++;
var maxLength = stream.length;
while (stream[this._current] !== "'" && this._current < maxLength) {
// You can escape a single quote and you can escape an escape.
var current = this._current;
if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
stream[current + 1] === "'")) {
current += 2;
} else {
current++;
}
this._current = current;
}
this._current++;
var literal = stream.slice(start + 1, this._current - 1);
return literal.replace("\\'", "'");
},
_consumeNumber: function(stream) {
var start = this._current;
this._current++;
var maxLength = stream.length;
while (isNum(stream[this._current]) && this._current < maxLength) {
this._current++;
}
var value = parseInt(stream.slice(start, this._current));
return {type: TOK_NUMBER, value: value, start: start};
},
_consumeLBracket: function(stream) {
var start = this._current;
this._current++;
if (stream[this._current] === "?") {
this._current++;
return {type: TOK_FILTER, value: "[?", start: start};
} else if (stream[this._current] === "]") {
this._current++;
return {type: TOK_FLATTEN, value: "[]", start: start};
} else {
return {type: TOK_LBRACKET, value: "[", start: start};
}
},
_consumeOperator: function(stream) {
var start = this._current;
var startingChar = stream[start];
this._current++;
if (startingChar === "!") {
if (stream[this._current] === "=") {
this._current++;
return {type: TOK_NE, value: "!=", start: start};
} else {
return {type: TOK_NOT, value: "!", start: start};
}
} else if (startingChar === "<") {
if (stream[this._current] === "=") {
this._current++;
return {type: TOK_LTE, value: "<=", start: start};
} else {
return {type: TOK_LT, value: "<", start: start};
}
} else if (startingChar === ">") {
if (stream[this._current] === "=") {
this._current++;
return {type: TOK_GTE, value: ">=", start: start};
} else {
return {type: TOK_GT, value: ">", start: start};
}
} else if (startingChar === "=") {
if (stream[this._current] === "=") {
this._current++;
return {type: TOK_EQ, value: "==", start: start};
}
}
},
_consumeLiteral: function(stream) {
this._current++;
var start = this._current;
var maxLength = stream.length;
var literal;
while(stream[this._current] !== "`" && this._current < maxLength) {
// You can escape a literal char or you can escape the escape.
var current = this._current;
if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
stream[current + 1] === "`")) {
current += 2;
} else {
current++;
}
this._current = current;
}
var literalString = trimLeft(stream.slice(start, this._current));
literalString = literalString.replace("\\`", "`");
if (this._looksLikeJSON(literalString)) {
literal = JSON.parse(literalString);
} else {
// Try to JSON parse it as "<literal>"
literal = JSON.parse("\"" + literalString + "\"");
}
// +1 gets us to the ending "`", +1 to move on to the next char.
this._current++;
return literal;
},
_looksLikeJSON: function(literalString) {
var startingChars = "[{\"";
var jsonLiterals = ["true", "false", "null"];
var numberLooking = "-0123456789";
if (literalString === "") {
return false;
} else if (startingChars.indexOf(literalString[0]) >= 0) {
return true;
} else if (jsonLiterals.indexOf(literalString) >= 0) {
return true;
} else if (numberLooking.indexOf(literalString[0]) >= 0) {
try {
JSON.parse(literalString);
return true;
} catch (ex) {
return false;
}
} else {
return false;
}
}
};
var bindingPower = {};
bindingPower[TOK_EOF] = 0;
bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0;
bindingPower[TOK_QUOTEDIDENTIFIER] = 0;
bindingPower[TOK_RBRACKET] = 0;
bindingPower[TOK_RPAREN] = 0;
bindingPower[TOK_COMMA] = 0;
bindingPower[TOK_RBRACE] = 0;
bindingPower[TOK_NUMBER] = 0;
bindingPower[TOK_CURRENT] = 0;
bindingPower[TOK_EXPREF] = 0;
bindingPower[TOK_PIPE] = 1;
bindingPower[TOK_OR] = 2;
bindingPower[TOK_AND] = 3;
bindingPower[TOK_EQ] = 5;
bindingPower[TOK_GT] = 5;
bindingPower[TOK_LT] = 5;
bindingPower[TOK_GTE] = 5;
bindingPower[TOK_LTE] = 5;
bindingPower[TOK_NE] = 5;
bindingPower[TOK_FLATTEN] = 9;
bindingPower[TOK_STAR] = 20;
bindingPower[TOK_FILTER] = 21;
bindingPower[TOK_DOT] = 40;
bindingPower[TOK_NOT] = 45;
bindingPower[TOK_LBRACE] = 50;
bindingPower[TOK_LBRACKET] = 55;
bindingPower[TOK_LPAREN] = 60;
function Parser() {
}
Parser.prototype = {
parse: function(expression) {
this._loadTokens(expression);
this.index = 0;
var ast = this.expression(0);
if (this._lookahead(0) !== TOK_EOF) {
var t = this._lookaheadToken(0);
var error = new Error(
"Unexpected token type: " + t.type + ", value: " + t.value);
error.name = "ParserError";
throw error;
}
return ast;
},
_loadTokens: function(expression) {
var lexer = new Lexer();
var tokens = lexer.tokenize(expression);
tokens.push({type: TOK_EOF, value: "", start: expression.length});
this.tokens = tokens;
},
expression: function(rbp) {
var leftToken = this._lookaheadToken(0);
this._advance();
var left = this.nud(leftToken);
var currentToken = this._lookahead(0);
while (rbp < bindingPower[currentToken]) {
this._advance();
left = this.led(currentToken, left);
currentToken = this._lookahead(0);
}
return left;
},
_lookahead: function(number) {
return this.tokens[this.index + number].type;
},
_lookaheadToken: function(number) {
return this.tokens[this.index + number];
},
_advance: function() {
this.index++;
},
nud: function(token) {
var left;
var right;
var expression;
switch (token.type) {
case TOK_LITERAL:
return {type: "Literal", value: token.value};
case TOK_UNQUOTEDIDENTIFIER:
return {type: "Field", name: token.value};
case TOK_QUOTEDIDENTIFIER:
var node = {type: "Field", name: token.value};
if (this._lookahead(0) === TOK_LPAREN) {
throw new Error("Quoted identifier not allowed for function names.");
} else {
return node;
}
break;
case TOK_NOT:
right = this.expression(bindingPower.Not);
return {type: "NotExpression", children: [right]};
case TOK_STAR:
left = {type: "Identity"};
right = null;
if (this._lookahead(0) === TOK_RBRACKET) {
// This can happen in a multiselect,
// [a, b, *]
right = {type: "Identity"};
} else {
right = this._parseProjectionRHS(bindingPower.Star);
}
return {type: "ValueProjection", children: [left, right]};
case TOK_FILTER:
return this.led(token.type, {type: "Identity"});
case TOK_LBRACE:
return this._parseMultiselectHash();
case TOK_FLATTEN:
left = {type: TOK_FLATTEN, children: [{type: "Identity"}]};
right = this._parseProjectionRHS(bindingPower.Flatten);
return {type: "Projection", children: [left, right]};
case TOK_LBRACKET:
if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) {
right = this._parseIndexExpression();
return this._projectIfSlice({type: "Identity"}, right);
} else if (this._lookahead(0) === TOK_STAR &&
this._lookahead(1) === TOK_RBRACKET) {
this._advance();
this._advance();
right = this._parseProjectionRHS(bindingPower.Star);
return {type: "Projection",
children: [{type: "Identity"}, right]};
} else {
return this._parseMultiselectList();
}
break;
case TOK_CURRENT:
return {type: TOK_CURRENT};
case TOK_EXPREF:
expression = this.expression(bindingPower.Expref);
return {type: "ExpressionReference", children: [expression]};
case TOK_LPAREN:
var args = [];
while (this._lookahead(0) !== TOK_RPAREN) {
if (this._lookahead(0) === TOK_CURRENT) {
expression = {type: TOK_CURRENT};
this._advance();
} else {
expression = this.expression(0);
}
args.push(expression);
}
this._match(TOK_RPAREN);
return args[0];
default:
this._errorToken(token);
}
},
led: function(tokenName, left) {
var right;
switch(tokenName) {
case TOK_DOT:
var rbp = bindingPower.Dot;
if (this._lookahead(0) !== TOK_STAR) {
right = this._parseDotRHS(rbp);
return {type: "Subexpression", children: [left, right]};
} else {
// Creating a projection.
this._advance();
right = this._parseProjectionRHS(rbp);
return {type: "ValueProjection", children: [left, right]};
}
break;
case TOK_PIPE:
right = this.expression(bindingPower.Pipe);
return {type: TOK_PIPE, children: [left, right]};
case TOK_OR:
right = this.expression(bindingPower.Or);
return {type: "OrExpression", children: [left, right]};
case TOK_AND:
right = this.expression(bindingPower.And);
return {type: "AndExpression", children: [left, right]};
case TOK_LPAREN:
var name = left.name;
var args = [];
var expression, node;
while (this._lookahead(0) !== TOK_RPAREN) {
if (this._lookahead(0) === TOK_CURRENT) {
expression = {type: TOK_CURRENT};
this._advance();
} else {
expression = this.expression(0);
}
if (this._lookahead(0) === TOK_COMMA) {
this._match(TOK_COMMA);
}
args.push(expression);
}
this._match(TOK_RPAREN);
node = {type: "Function", name: name, children: args};
return node;
case TOK_FILTER:
var condition = this.expression(0);
this._match(TOK_RBRACKET);
if (this._lookahead(0) === TOK_FLATTEN) {
right = {type: "Identity"};
} else {
right = this._parseProjectionRHS(bindingPower.Filter);
}
return {type: "FilterProjection", children: [left, right, condition]};
case TOK_FLATTEN:
var leftNode = {type: TOK_FLATTEN, children: [left]};
var rightNode = this._parseProjectionRHS(bindingPower.Flatten);
return {type: "Projection", children: [leftNode, rightNode]};
case TOK_EQ:
case TOK_NE:
case TOK_GT:
case TOK_GTE:
case TOK_LT:
case TOK_LTE:
return this._parseComparator(left, tokenName);
case TOK_LBRACKET:
var token = this._lookaheadToken(0);
if (token.type === TOK_NUMBER || token.type === TOK_COLON) {
right = this._parseIndexExpression();
return this._projectIfSlice(left, right);
} else {
this._match(TOK_STAR);
this._match(TOK_RBRACKET);
right = this._parseProjectionRHS(bindingPower.Star);
return {type: "Projection", children: [left, right]};
}
break;
default:
this._errorToken(this._lookaheadToken(0));
}
},
_match: function(tokenType) {
if (this._lookahead(0) === tokenType) {
this._advance();
} else {
var t = this._lookaheadToken(0);
var error = new Error("Expected " + tokenType + ", got: " + t.type);
error.name = "ParserError";
throw error;
}
},
_errorToken: function(token) {
var error = new Error("Invalid token (" +
token.type + "): \"" +
token.value + "\"");
error.name = "ParserError";
throw error;
},
_parseIndexExpression: function() {
if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) {
return this._parseSliceExpression();
} else {
var node = {
type: "Index",
value: this._lookaheadToken(0).value};
this._advance();
this._match(TOK_RBRACKET);
return node;
}
},
_projectIfSlice: function(left, right) {
var indexExpr = {type: "IndexExpression", children: [left, right]};
if (right.type === "Slice") {
return {
type: "Projection",
children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)]
};
} else {
return indexExpr;
}
},
_parseSliceExpression: function() {
// [start:end:step] where each part is optional, as well as the last
// colon.
var parts = [null, null, null];
var index = 0;
var currentToken = this._lookahead(0);
while (currentToken !== TOK_RBRACKET && index < 3) {
if (currentToken === TOK_COLON) {
index++;
this._advance();
} else if (currentToken === TOK_NUMBER) {
parts[index] = this._lookaheadToken(0).value;
this._advance();
} else {
var t = this._lookahead(0);
var error = new Error("Syntax error, unexpected token: " +
t.value + "(" + t.type + ")");
error.name = "Parsererror";
throw error;
}
currentToken = this._lookahead(0);
}
this._match(TOK_RBRACKET);
return {
type: "Slice",
children: parts
};
},
_parseComparator: function(left, comparator) {
var right = this.expression(bindingPower[comparator]);
return {type: "Comparator", name: comparator, children: [left, right]};
},
_parseDotRHS: function(rbp) {
var lookahead = this._lookahead(0);
var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR];
if (exprTokens.indexOf(lookahead) >= 0) {
return this.expression(rbp);
} else if (lookahead === TOK_LBRACKET) {
this._match(TOK_LBRACKET);
return this._parseMultiselectList();
} else if (lookahead === TOK_LBRACE) {
this._match(TOK_LBRACE);
return this._parseMultiselectHash();
}
},
_parseProjectionRHS: function(rbp) {
var right;
if (bindingPower[this._lookahead(0)] < 10) {
right = {type: "Identity"};
} else if (this._lookahead(0) === TOK_LBRACKET) {
right = this.expression(rbp);
} else if (this._lookahead(0) === TOK_FILTER) {
right = this.expression(rbp);
} else if (this._lookahead(0) === TOK_DOT) {
this._match(TOK_DOT);
right = this._parseDotRHS(rbp);
} else {
var t = this._lookaheadToken(0);
var error = new Error("Sytanx error, unexpected token: " +
t.value + "(" + t.type + ")");
error.name = "ParserError";
throw error;
}
return right;
},
_parseMultiselectList: function() {
var expressions = [];
while (this._lookahead(0) !== TOK_RBRACKET) {
var expression = this.expression(0);
expressions.push(expression);
if (this._lookahead(0) === TOK_COMMA) {
this._match(TOK_COMMA);
if (this._lookahead(0) === TOK_RBRACKET) {
throw new Error("Unexpected token Rbracket");
}
}
}
this._match(TOK_RBRACKET);
return {type: "MultiSelectList", children: expressions};
},
_parseMultiselectHash: function() {
var pairs = [];
var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER];
var keyToken, keyName, value, node;
for (;;) {
keyToken = this._lookaheadToken(0);
if (identifierTypes.indexOf(keyToken.type) < 0) {
throw new Error("Expecting an identifier token, got: " +
keyToken.type);
}
keyName = keyToken.value;
this._advance();
this._match(TOK_COLON);
value = this.expression(0);
node = {type: "KeyValuePair", name: keyName, value: value};
pairs.push(node);
if (this._lookahead(0) === TOK_COMMA) {
this._match(TOK_COMMA);
} else if (this._lookahead(0) === TOK_RBRACE) {
this._match(TOK_RBRACE);
break;
}
}
return {type: "MultiSelectHash", children: pairs};
}
};
function TreeInterpreter(runtime) {
this.runtime = runtime;
}
TreeInterpreter.prototype = {
search: function(node, value) {
return this.visit(node, value);
},
visit: function(node, value) {
var matched, current, result, first, second, field, left, right, collected, i;
switch (node.type) {
case "Field":
if (value === null ) {
return null;
} else if (isObject(value)) {
field = value[node.name];
if (field === undefined) {
return null;
} else {
return field;
}
} else {
return null;
}
break;
case "Subexpression":
result = this.visit(node.children[0], value);
for (i = 1; i < node.children.length; i++) {
result = this.visit(node.children[1], result);
if (result === null) {
return null;
}
}
return result;
case "IndexExpression":
left = this.visit(node.children[0], value);
right = this.visit(node.children[1], left);
return right;
case "Index":
if (!isArray(value)) {
return null;
}
var index = node.value;
if (index < 0) {
index = value.length + index;
}
result = value[index];
if (result === undefined) {
result = null;
}
return result;
case "Slice":
if (!isArray(value)) {
return null;
}
var sliceParams = node.children.slice(0);
var computed = this.computeSliceParams(value.length, sliceParams);
var start = computed[0];
var stop = computed[1];
var step = computed[2];
result = [];
if (step > 0) {
for (i = start; i < stop; i += step) {
result.push(value[i]);
}
} else {
for (i = start; i > stop; i += step) {
result.push(value[i]);
}
}
return result;
case "Projection":
// Evaluate left child.
var base = this.visit(node.children[0], value);
if (!isArray(base)) {
return null;
}
collected = [];
for (i = 0; i < base.length; i++) {
current = this.visit(node.children[1], base[i]);
if (current !== null) {
collected.push(current);
}
}
return collected;
case "ValueProjection":
// Evaluate left child.
base = this.visit(node.children[0], value);
if (!isObject(base)) {
return null;
}
collected = [];
var values = objValues(base);
for (i = 0; i < values.length; i++) {
current = this.visit(node.children[1], values[i]);
if (current !== null) {
collected.push(current);
}
}
return collected;
case "FilterProjection":
base = this.visit(node.children[0], value);
if (!isArray(base)) {
return null;
}
var filtered = [];
var finalResults = [];
for (i = 0; i < base.length; i++) {
matched = this.visit(node.children[2], base[i]);
if (!isFalse(matched)) {
filtered.push(base[i]);
}
}
for (var j = 0; j < filtered.length; j++) {
current = this.visit(node.children[1], filtered[j]);
if (current !== null) {
finalResults.push(current);
}
}
return finalResults;
case "Comparator":
first = this.visit(node.children[0], value);
second = this.visit(node.children[1], value);
switch(node.name) {
case TOK_EQ:
result = strictDeepEqual(first, second);
break;
case TOK_NE:
result = !strictDeepEqual(first, second);
break;
case TOK_GT:
result = first > second;
break;
case TOK_GTE:
result = first >= second;
break;
case TOK_LT:
result = first < second;
break;
case TOK_LTE:
result = first <= second;
break;
default:
throw new Error("Unknown comparator: " + node.name);
}
return result;
case TOK_FLATTEN:
var original = this.visit(node.children[0], value);
if (!isArray(original)) {
return null;
}
var merged = [];
for (i = 0; i < original.length; i++) {
current = original[i];
if (isArray(current)) {
merged.push.apply(merged, current);
} else {
merged.push(current);
}
}
return merged;
case "Identity":
return value;
case "MultiSelectList":
if (value === null) {
return null;
}
collected = [];
for (i = 0; i < node.children.length; i++) {
collected.push(this.visit(node.children[i], value));
}
return collected;
case "MultiSelectHash":
if (value === null) {
return null;
}
collected = {};
var child;
for (i = 0; i < node.children.length; i++) {
child = node.children[i];
collected[child.name] = this.visit(child.value, value);
}
return collected;
case "OrExpression":
matched = this.visit(node.children[0], value);
if (isFalse(matched)) {
matched = this.visit(node.children[1], value);
}
return matched;
case "AndExpression":
first = this.visit(node.children[0], value);
if (isFalse(first) === true) {
return first;
}
return this.visit(node.children[1], value);
case "NotExpression":
first = this.visit(node.children[0], value);
return isFalse(first);
case "Literal":
return node.value;
case TOK_PIPE:
left = this.visit(node.children[0], value);
return this.visit(node.children[1], left);
case TOK_CURRENT:
return value;
case "Function":
var resolvedArgs = [];
for (i = 0; i < node.children.length; i++) {
resolvedArgs.push(this.visit(node.children[i], value));
}
return this.runtime.callFunction(node.name, resolvedArgs);
case "ExpressionReference":
var refNode = node.children[0];
// Tag the node with a specific attribute so the type
// checker verify the type.
refNode.jmespathType = TOK_EXPREF;
return refNode;
default:
throw new Error("Unknown node type: " + node.type);
}
},
computeSliceParams: function(arrayLength, sliceParams) {
var start = sliceParams[0];
var stop = sliceParams[1];
var step = sliceParams[2];
var computed = [null, null, null];
if (step === null) {
step = 1;
} else if (step === 0) {
var error = new Error("Invalid slice, step cannot be 0");
error.name = "RuntimeError";
throw error;
}
var stepValueNegative = step < 0 ? true : false;
if (start === null) {
start = stepValueNegative ? arrayLength - 1 : 0;
} else {
start = this.capSliceRange(arrayLength, start, step);
}
if (stop === null) {
stop = stepValueNegative ? -1 : arrayLength;
} else {
stop = this.capSliceRange(arrayLength, stop, step);
}
computed[0] = start;
computed[1] = stop;
computed[2] = step;
return computed;
},
capSliceRange: function(arrayLength, actualValue, step) {
if (actualValue < 0) {
actualValue += arrayLength;
if (actualValue < 0) {
actualValue = step < 0 ? -1 : 0;
}
} else if (actualValue >= arrayLength) {
actualValue = step < 0 ? arrayLength - 1 : arrayLength;
}
return actualValue;
}
};
function Runtime(interpreter) {
this._interpreter = interpreter;
this.functionTable = {
// name: [function, <signature>]
// The <signature> can be:
//
// {
// args: [[type1, type2], [type1, type2]],
// variadic: true|false
// }
//
// Each arg in the arg list is a list of valid types
// (if the function is overloaded and supports multiple
// types. If the type is "any" then no type checking
// occurs on the argument. Variadic is optional
// and if not provided is assumed to be false.
abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]},
avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},
ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]},
contains: {
_func: this._functionContains,
_signature: [{types: [TYPE_STRING, TYPE_ARRAY]},
{types: [TYPE_ANY]}]},
"ends_with": {
_func: this._functionEndsWith,
_signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},
floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]},
length: {
_func: this._functionLength,
_signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]},
map: {
_func: this._functionMap,
_signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]},
max: {
_func: this._functionMax,
_signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},
"merge": {
_func: this._functionMerge,
_signature: [{types: [TYPE_OBJECT], variadic: true}]
},
"max_by": {
_func: this._functionMaxBy,
_signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
},
sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},
"starts_with": {
_func: this._functionStartsWith,
_signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},
min: {
_func: this._functionMin,
_signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},
"min_by": {
_func: this._functionMinBy,
_signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
},
type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]},
keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]},
values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]},
sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]},
"sort_by": {
_func: this._functionSortBy,
_signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
},
join: {
_func: this._functionJoin,
_signature: [
{types: [TYPE_STRING]},
{types: [TYPE_ARRAY_STRING]}
]
},
reverse: {
_func: this._functionReverse,
_signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]},
"to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]},
"to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]},
"to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]},
"not_null": {
_func: this._functionNotNull,
_signature: [{types: [TYPE_ANY], variadic: true}]
}
};
}
Runtime.prototype = {
callFunction: function(name, resolvedArgs) {
var functionEntry = this.functionTable[name];
if (functionEntry === undefined) {
throw new Error("Unknown function: " + name + "()");
}
this._validateArgs(name, resolvedArgs, functionEntry._signature);
return functionEntry._func.call(this, resolvedArgs);
},
_validateArgs: function(name, args, signature) {
// Validating the args requires validating
// the correct arity and the correct type of each arg.
// If the last argument is declared as variadic, then we need
// a minimum number of args to be required. Otherwise it has to
// be an exact amount.
var pluralized;
if (signature[signature.length - 1].variadic) {
if (args.length < signature.length) {
pluralized = signature.length === 1 ? " argument" : " arguments";
throw new Error("ArgumentError: " + name + "() " +
"takes at least" + signature.length + pluralized +
" but received " + args.length);
}
} else if (args.length !== signature.length) {
pluralized = signature.length === 1 ? " argument" : " arguments";
throw new Error("ArgumentError: " + name + "() " +
"takes " + signature.length + pluralized +
" but received " + args.length);
}
var currentSpec;
var actualType;
var typeMatched;
for (var i = 0; i < signature.length; i++) {
typeMatched = false;
currentSpec = signature[i].types;
actualType = this._getTypeName(args[i]);
for (var j = 0; j < currentSpec.length; j++) {
if (this._typeMatches(actualType, currentSpec[j], args[i])) {
typeMatched = true;
break;
}
}
if (!typeMatched) {
throw new Error("TypeError: " + name + "() " +
"expected argument " + (i + 1) +
" to be type " + currentSpec +
" but received type " + actualType +
" instead.");
}
}
},
_typeMatches: function(actual, expected, argValue) {
if (expected === TYPE_ANY) {
return true;
}
if (expected === TYPE_ARRAY_STRING ||
expected === TYPE_ARRAY_NUMBER ||
expected === TYPE_ARRAY) {
// The expected type can either just be array,
// or it can require a specific subtype (array of numbers).
//
// The simplest case is if "array" with no subtype is specified.
if (expected === TYPE_ARRAY) {
return actual === TYPE_ARRAY;
} else if (actual === TYPE_ARRAY) {
// Otherwise we need to check subtypes.
// I think this has potential to be improved.
var subtype;
if (expected === TYPE_ARRAY_NUMBER) {
subtype = TYPE_NUMBER;
} else if (expected === TYPE_ARRAY_STRING) {
subtype = TYPE_STRING;
}
for (var i = 0; i < argValue.length; i++) {
if (!this._typeMatches(
this._getTypeName(argValue[i]), subtype,
argValue[i])) {
return false;
}
}
return true;
}
} else {
return actual === expected;
}
},
_getTypeName: function(obj) {
switch (Object.prototype.toString.call(obj)) {
case "[object String]":
return TYPE_STRING;
case "[object Number]":
return TYPE_NUMBER;
case "[object Array]":
return TYPE_ARRAY;
case "[object Boolean]":
return TYPE_BOOLEAN;
case "[object Null]":
return TYPE_NULL;
case "[object Object]":
// Check if it's an expref. If it has, it's been
// tagged with a jmespathType attr of 'Expref';
if (obj.jmespathType === TOK_EXPREF) {
return TYPE_EXPREF;
} else {
return TYPE_OBJECT;
}
}
},
_functionStartsWith: function(resolvedArgs) {
return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0;
},
_functionEndsWith: function(resolvedArgs) {
var searchStr = resolvedArgs[0];
var suffix = resolvedArgs[1];
return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1;
},
_functionReverse: function(resolvedArgs) {
var typeName = this._getTypeName(resolvedArgs[0]);
if (typeName === TYPE_STRING) {
var originalStr = resolvedArgs[0];
var reversedStr = "";
for (var i = originalStr.length - 1; i >= 0; i--) {
reversedStr += originalStr[i];
}
return reversedStr;
} else {
var reversedArray = resolvedArgs[0].slice(0);
reversedArray.reverse();
return reversedArray;
}
},
_functionAbs: function(resolvedArgs) {
return Math.abs(resolvedArgs[0]);
},
_functionCeil: function(resolvedArgs) {
return Math.ceil(resolvedArgs[0]);
},
_functionAvg: function(resolvedArgs) {
var sum = 0;
var inputArray = resolvedArgs[0];
for (var i = 0; i < inputArray.length; i++) {
sum += inputArray[i];
}
return sum / inputArray.length;
},
_functionContains: function(resolvedArgs) {
return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0;
},
_functionFloor: function(resolvedArgs) {
return Math.floor(resolvedArgs[0]);
},
_functionLength: function(resolvedArgs) {
if (!isObject(resolvedArgs[0])) {
return resolvedArgs[0].length;
} else {
// As far as I can tell, there's no way to get the length
// of an object without O(n) iteration through the object.
return Object.keys(resolvedArgs[0]).length;
}
},
_functionMap: function(resolvedArgs) {
var mapped = [];
var interpreter = this._interpreter;
var exprefNode = resolvedArgs[0];
var elements = resolvedArgs[1];
for (var i = 0; i < elements.length; i++) {
mapped.push(interpreter.visit(exprefNode, elements[i]));
}
return mapped;
},
_functionMerge: function(resolvedArgs) {
var merged = {};
for (var i = 0; i < resolvedArgs.length; i++) {
var current = resolvedArgs[i];
for (var key in current) {
merged[key] = current[key];
}
}
return merged;
},
_functionMax: function(resolvedArgs) {
if (resolvedArgs[0].length > 0) {
var typeName = this._getTypeName(resolvedArgs[0][0]);
if (typeName === TYPE_NUMBER) {
return Math.max.apply(Math, resolvedArgs[0]);
} else {
var elements = resolvedArgs[0];
var maxElement = elements[0];
for (var i = 1; i < elements.length; i++) {
if (maxElement.localeCompare(elements[i]) < 0) {
maxElement = elements[i];
}
}
return maxElement;
}
} else {
return null;
}
},
_functionMin: function(resolvedArgs) {
if (resolvedArgs[0].length > 0) {
var typeName = this._getTypeName(resolvedArgs[0][0]);
if (typeName === TYPE_NUMBER) {
return Math.min.apply(Math, resolvedArgs[0]);
} else {
var elements = resolvedArgs[0];
var minElement = elements[0];
for (var i = 1; i < elements.length; i++) {
if (elements[i].localeCompare(minElement) < 0) {
minElement = elements[i];
}
}
return minElement;
}
} else {
return null;
}
},
_functionSum: function(resolvedArgs) {
var sum = 0;
var listToSum = resolvedArgs[0];
for (var i = 0; i < listToSum.length; i++) {
sum += listToSum[i];
}
return sum;
},
_functionType: function(resolvedArgs) {
switch (this._getTypeName(resolvedArgs[0])) {
case TYPE_NUMBER:
return "number";
case TYPE_STRING:
return "string";
case TYPE_ARRAY:
return "array";
case TYPE_OBJECT:
return "object";
case TYPE_BOOLEAN:
return "boolean";
case TYPE_EXPREF:
return "expref";
case TYPE_NULL:
return "null";
}
},
_functionKeys: function(resolvedArgs) {
return Object.keys(resolvedArgs[0]);
},
_functionValues: function(resolvedArgs) {
var obj = resolvedArgs[0];
var keys = Object.keys(obj);
var values = [];
for (var i = 0; i < keys.length; i++) {
values.push(obj[keys[i]]);
}
return values;
},
_functionJoin: function(resolvedArgs) {
var joinChar = resolvedArgs[0];
var listJoin = resolvedArgs[1];
return listJoin.join(joinChar);
},
_functionToArray: function(resolvedArgs) {
if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) {
return resolvedArgs[0];
} else {
return [resolvedArgs[0]];
}
},
_functionToString: function(resolvedArgs) {
if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) {
return resolvedArgs[0];
} else {
return JSON.stringify(resolvedArgs[0]);
}
},
_functionToNumber: function(resolvedArgs) {
var typeName = this._getTypeName(resolvedArgs[0]);
var convertedValue;
if (typeName === TYPE_NUMBER) {
return resolvedArgs[0];
} else if (typeName === TYPE_STRING) {
convertedValue = +resolvedArgs[0];
if (!isNaN(convertedValue)) {
return convertedValue;
}
}
return null;
},
_functionNotNull: function(resolvedArgs) {
for (var i = 0; i < resolvedArgs.length; i++) {
if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) {
return resolvedArgs[i];
}
}
return null;
},
_functionSort: function(resolvedArgs) {
var sortedArray = resolvedArgs[0].slice(0);
sortedArray.sort();
return sortedArray;
},
_functionSortBy: function(resolvedArgs) {
var sortedArray = resolvedArgs[0].slice(0);
if (sortedArray.length === 0) {
return sortedArray;
}
var interpreter = this._interpreter;
var exprefNode = resolvedArgs[1];
var requiredType = this._getTypeName(
interpreter.visit(exprefNode, sortedArray[0]));
if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) {
throw new Error("TypeError");
}
var that = this;
// In order to get a stable sort out of an unstable
// sort algorithm, we decorate/sort/undecorate (DSU)
// by creating a new list of [index, element] pairs.
// In the cmp function, if the evaluated elements are
// equal, then the index will be used as the tiebreaker.
// After the decorated list has been sorted, it will be
// undecorated to extract the original elements.
var decorated = [];
for (var i = 0; i < sortedArray.length; i++) {
decorated.push([i, sortedArray[i]]);
}
decorated.sort(function(a, b) {
var exprA = interpreter.visit(exprefNode, a[1]);
var exprB = interpreter.visit(exprefNode, b[1]);
if (that._getTypeName(exprA) !== requiredType) {
throw new Error(
"TypeError: expected " + requiredType + ", received " +
that._getTypeName(exprA));
} else if (that._getTypeName(exprB) !== requiredType) {
throw new Error(
"TypeError: expected " + requiredType + ", received " +
that._getTypeName(exprB));
}
if (exprA > exprB) {
return 1;
} else if (exprA < exprB) {
return -1;
} else {
// If they're equal compare the items by their
// order to maintain relative order of equal keys
// (i.e. to get a stable sort).
return a[0] - b[0];
}
});
// Undecorate: extract out the original list elements.
for (var j = 0; j < decorated.length; j++) {
sortedArray[j] = decorated[j][1];
}
return sortedArray;
},
_functionMaxBy: function(resolvedArgs) {
var exprefNode = resolvedArgs[1];
var resolvedArray = resolvedArgs[0];
var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);
var maxNumber = -Infinity;
var maxRecord;
var current;
for (var i = 0; i < resolvedArray.length; i++) {
current = keyFunction(resolvedArray[i]);
if (current > maxNumber) {
maxNumber = current;
maxRecord = resolvedArray[i];
}
}
return maxRecord;
},
_functionMinBy: function(resolvedArgs) {
var exprefNode = resolvedArgs[1];
var resolvedArray = resolvedArgs[0];
var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);
var minNumber = Infinity;
var minRecord;
var current;
for (var i = 0; i < resolvedArray.length; i++) {
current = keyFunction(resolvedArray[i]);
if (current < minNumber) {
minNumber = current;
minRecord = resolvedArray[i];
}
}
return minRecord;
},
createKeyFunction: function(exprefNode, allowedTypes) {
var that = this;
var interpreter = this._interpreter;
var keyFunc = function(x) {
var current = interpreter.visit(exprefNode, x);
if (allowedTypes.indexOf(that._getTypeName(current)) < 0) {
var msg = "TypeError: expected one of " + allowedTypes +
", received " + that._getTypeName(current);
throw new Error(msg);
}
return current;
};
return keyFunc;
}
};
function compile(stream) {
var parser = new Parser();
var ast = parser.parse(stream);
return ast;
}
function tokenize(stream) {
var lexer = new Lexer();
return lexer.tokenize(stream);
}
function search(data, expression) {
var parser = new Parser();
// This needs to be improved. Both the interpreter and runtime depend on
// each other. The runtime needs the interpreter to support exprefs.
// There's likely a clean way to avoid the cyclic dependency.
var runtime = new Runtime();
var interpreter = new TreeInterpreter(runtime);
runtime._interpreter = interpreter;
var node = parser.parse(expression);
return interpreter.search(node, data);
}
exports.tokenize = tokenize;
exports.compile = compile;
exports.search = search;
exports.strictDeepEqual = strictDeepEqual;
})(typeof exports === "undefined" ? this.jmespath = {} : exports);
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| support.js | 88.24% | (15 / 17) | 75% | (3 / 4) | 50% | (1 / 2) | 93.75% | (15 / 16) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | var isNative = require('./lang/isNative');
/** Used to detect functions containing a `this` reference. */
var reThis = /\bthis\b/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to detect DOM support. */
var document = (document = global.window) && document.document;
/** Native method references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* An object environment feature flags.
*
* @static
* @memberOf _
* @type Object
*/
var support = {};
(function(x) {
/**
* Detect if functions can be decompiled by `Function#toString`
* (all but Firefox OS certified apps, older Opera mobile browsers, and
* the PlayStation 3; forced `false` for Windows 8 apps).
*
* @memberOf _.support
* @type boolean
*/
support.funcDecomp = !isNative(global.WinRTError) && reThis.test(function() { return this; });
/**
* Detect if `Function#name` is supported (all but IE).
*
* @memberOf _.support
* @type boolean
*/
support.funcNames = typeof Function.name == 'string';
/**
* Detect if the DOM is supported.
*
* @memberOf _.support
* @type boolean
*/
try {
support.dom = document.createDocumentFragment().nodeType === 11;
} catch(e) {
support.dom = false;
}
/**
* Detect if `arguments` object indexes are non-enumerable.
*
* In Firefox < 4, IE < 9, PhantomJS, and Safari < 5.1 `arguments` object
* indexes are non-enumerable. Chrome < 25 and Node.js < 0.11.0 treat
* `arguments` object indexes as non-enumerable and fail `hasOwnProperty`
* checks for indexes that exceed their function's formal parameters with
* associated values of `0`.
*
* @memberOf _.support
* @type boolean
*/
try {
support.nonEnumArgs = !propertyIsEnumerable.call(arguments, 1);
} catch(e) {
support.nonEnumArgs = true;
}
}(0, 0));
module.exports = support;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| every.js | 42.86% | (3 / 7) | 0% | (0 / 6) | 0% | (0 / 1) | 42.86% | (3 / 7) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | 1 1 1 | var arrayEvery = require('../internal/arrayEvery'),
baseCallback = require('../internal/baseCallback'),
baseEvery = require('../internal/baseEvery'),
isArray = require('../lang/isArray');
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* The predicate is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @alias all
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false }
* ];
*
* // using the `_.matches` callback shorthand
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
* // using the `_.matchesProperty` callback shorthand
* _.every(users, 'active', false);
* // => true
*
* // using the `_.property` callback shorthand
* _.every(users, 'active');
* // => false
*/
function every(collection, predicate, thisArg) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (typeof predicate != 'function' || typeof thisArg != 'undefined') {
predicate = baseCallback(predicate, thisArg, 3);
}
return func(collection, predicate);
}
module.exports = every;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| arrayEvery.js | 28.57% | (2 / 7) | 0% | (0 / 2) | 0% | (0 / 1) | 28.57% | (2 / 7) | |
| baseAssign.js | 25% | (3 / 12) | 0% | (0 / 9) | 0% | (0 / 1) | 25% | (3 / 12) | |
| baseCallback.js | 27.27% | (3 / 11) | 0% | (0 / 12) | 0% | (0 / 1) | 27.27% | (3 / 11) | |
| baseCopy.js | 20% | (2 / 10) | 0% | (0 / 2) | 0% | (0 / 1) | 20% | (2 / 10) | |
| baseCreate.js | 50% | (5 / 10) | 0% | (0 / 4) | 33.33% | (1 / 3) | 50% | (5 / 10) | |
| baseEach.js | 27.27% | (3 / 11) | 0% | (0 / 6) | 0% | (0 / 1) | 27.27% | (3 / 11) | |
| baseEvery.js | 37.5% | (3 / 8) | 100% | (0 / 0) | 0% | (0 / 2) | 37.5% | (3 / 8) | |
| baseFor.js | 33.33% | (3 / 9) | 0% | (0 / 2) | 0% | (0 / 1) | 33.33% | (3 / 9) | |
| baseForOwn.js | 75% | (3 / 4) | 100% | (0 / 0) | 0% | (0 / 1) | 75% | (3 / 4) | |
| baseIsEqual.js | 33.33% | (3 / 9) | 0% | (0 / 14) | 0% | (0 / 1) | 33.33% | (3 / 9) | |
| baseIsEqualDeep.js | 17.5% | (7 / 40) | 0% | (0 / 40) | 0% | (0 / 1) | 17.5% | (7 / 40) | |
| baseIsFunction.js | 100% | (3 / 3) | 100% | (2 / 2) | 100% | (1 / 1) | 100% | (3 / 3) | |
| baseIsMatch.js | 20.83% | (5 / 24) | 0% | (0 / 18) | 0% | (0 / 1) | 20.83% | (5 / 24) | |
| baseMatches.js | 27.78% | (5 / 18) | 0% | (0 / 7) | 0% | (0 / 3) | 27.78% | (5 / 18) | |
| baseMatchesProperty.js | 37.5% | (3 / 8) | 0% | (0 / 6) | 0% | (0 / 3) | 37.5% | (3 / 8) | |
| baseProperty.js | 50% | (2 / 4) | 0% | (0 / 2) | 0% | (0 / 2) | 50% | (2 / 4) | |
| baseSetData.js | 60% | (3 / 5) | 50% | (1 / 2) | 0% | (0 / 1) | 60% | (3 / 5) | |
| baseToString.js | 80% | (4 / 5) | 50% | (2 / 4) | 100% | (1 / 1) | 80% | (4 / 5) | |
| bindCallback.js | 16.67% | (3 / 18) | 0% | (0 / 8) | 0% | (0 / 6) | 16.67% | (3 / 18) | |
| createAssigner.js | 18.18% | (4 / 22) | 0% | (0 / 22) | 50% | (1 / 2) | 18.18% | (4 / 22) | |
| equalArrays.js | 10% | (2 / 20) | 0% | (0 / 24) | 0% | (0 / 1) | 10% | (2 / 20) | |
| equalByTag.js | 33.33% | (3 / 9) | 0% | (0 / 12) | 0% | (0 / 1) | 33.33% | (3 / 9) | |
| equalObjects.js | 19.23% | (5 / 26) | 0% | (0 / 31) | 0% | (0 / 1) | 19.23% | (5 / 26) | |
| isBindable.js | 40% | (6 / 15) | 0% | (0 / 10) | 0% | (0 / 1) | 40% | (6 / 15) | |
| isIndex.js | 50% | (3 / 6) | 0% | (0 / 5) | 0% | (0 / 1) | 50% | (3 / 6) | |
| isIterateeCall.js | 23.08% | (3 / 13) | 0% | (0 / 12) | 0% | (0 / 1) | 23.08% | (3 / 13) | |
| isLength.js | 75% | (3 / 4) | 0% | (0 / 4) | 0% | (0 / 1) | 75% | (3 / 4) | |
| isObjectLike.js | 66.67% | (2 / 3) | 0% | (0 / 3) | 0% | (0 / 1) | 66.67% | (2 / 3) | |
| isStrictComparable.js | 75% | (3 / 4) | 0% | (0 / 4) | 0% | (0 / 1) | 75% | (3 / 4) | |
| metaMap.js | 100% | (4 / 4) | 100% | (4 / 4) | 100% | (0 / 0) | 100% | (4 / 4) | |
| shimKeys.js | 38.46% | (5 / 13) | 0% | (0 / 12) | 0% | (0 / 1) | 38.46% | (5 / 13) | |
| toObject.js | 75% | (3 / 4) | 0% | (0 / 2) | 0% | (0 / 1) | 75% | (3 / 4) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 1 1 | /**
* A specialized version of `_.every` for arrays without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
*/
function arrayEvery(array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
module.exports = arrayEvery;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 1 1 1 | var baseCopy = require('./baseCopy'),
keys = require('../object/keys');
/**
* The base implementation of `_.assign` without support for argument juggling,
* multiple sources, and `this` binding `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [customizer] The function to customize assigning values.
* @returns {Object} Returns the destination object.
*/
function baseAssign(object, source, customizer) {
var props = keys(source);
if (!customizer) {
return baseCopy(source, object, props);
}
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index],
value = object[key],
result = customizer(value, source[key], key, object, source);
if ((result === result ? (result !== value) : (value === value)) ||
(typeof value == 'undefined' && !(key in object))) {
object[key] = result;
}
}
return object;
}
module.exports = baseAssign;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 1 1 1 | var baseMatches = require('./baseMatches'),
baseMatchesProperty = require('./baseMatchesProperty'),
baseProperty = require('./baseProperty'),
bindCallback = require('./bindCallback'),
identity = require('../utility/identity'),
isBindable = require('./isBindable');
/**
* The base implementation of `_.callback` which supports specifying the
* number of arguments to provide to `func`.
*
* @private
* @param {*} [func=_.identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
function baseCallback(func, thisArg, argCount) {
var type = typeof func;
if (type == 'function') {
return (typeof thisArg != 'undefined' && isBindable(func))
? bindCallback(func, thisArg, argCount)
: func;
}
if (func == null) {
return identity;
}
if (type == 'object') {
return baseMatches(func);
}
return typeof thisArg == 'undefined'
? baseProperty(func + '')
: baseMatchesProperty(func + '', thisArg);
}
module.exports = baseCallback;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 1 1 | /**
* Copies the properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Object} [object={}] The object to copy properties to.
* @param {Array} props The property names to copy.
* @returns {Object} Returns `object`.
*/
function baseCopy(source, object, props) {
if (!props) {
props = object;
object = {};
}
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
object[key] = source[key];
}
return object;
}
module.exports = baseCopy;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 1 1 1 1 1 | var isObject = require('../lang/isObject');
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} prototype The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function Object() {}
return function(prototype) {
if (isObject(prototype)) {
Object.prototype = prototype;
var result = new Object;
Object.prototype = null;
}
return result || global.Object();
};
}());
module.exports = baseCreate;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 1 1 1 | var baseForOwn = require('./baseForOwn'),
isLength = require('./isLength'),
toObject = require('./toObject');
/**
* The base implementation of `_.forEach` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object|string} Returns `collection`.
*/
function baseEach(collection, iteratee) {
var length = collection ? collection.length : 0;
if (!isLength(length)) {
return baseForOwn(collection, iteratee);
}
var index = -1,
iterable = toObject(collection);
while (++index < length) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
}
module.exports = baseEach;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 1 1 1 | var baseEach = require('./baseEach');
/**
* The base implementation of `_.every` without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
*/
function baseEvery(collection, predicate) {
var result = true;
baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection);
return result;
});
return result;
}
module.exports = baseEvery;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 1 1 1 | var toObject = require('./toObject');
/**
* The base implementation of `baseForIn` and `baseForOwn` which iterates
* over `object` properties returned by `keysFunc` invoking `iteratee` for
* each property. Iterator functions may exit iteration early by explicitly
* returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
function baseFor(object, iteratee, keysFunc) {
var index = -1,
iterable = toObject(object),
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
}
module.exports = baseFor;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 1 1 1 | var baseFor = require('./baseFor'),
keys = require('../object/keys');
/**
* The base implementation of `_.forOwn` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return baseFor(object, iteratee, keys);
}
module.exports = baseForOwn;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 1 1 1 | var baseIsEqualDeep = require('./baseIsEqualDeep');
/**
* The base implementation of `_.isEqual` without support for `this` binding
* `customizer` functions.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparing values.
* @param {boolean} [isWhere] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, customizer, isWhere, stackA, stackB) {
// Exit early for identical values.
if (value === other) {
// Treat `+0` vs. `-0` as not equal.
return value !== 0 || (1 / value == 1 / other);
}
var valType = typeof value,
othType = typeof other;
// Exit early for unlike primitive values.
if ((valType != 'function' && valType != 'object' && othType != 'function' && othType != 'object') ||
value == null || other == null) {
// Return `false` unless both values are `NaN`.
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, customizer, isWhere, stackA, stackB);
}
module.exports = baseIsEqual;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | 1 1 1 1 1 1 1 | var equalArrays = require('./equalArrays'),
equalByTag = require('./equalByTag'),
equalObjects = require('./equalObjects'),
isArray = require('../lang/isArray'),
isTypedArray = require('../lang/isTypedArray');
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
objectTag = '[object Object]';
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the `toStringTag` of values.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* for more details.
*/
var objToString = objectProto.toString;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing objects.
* @param {boolean} [isWhere] Specify performing partial comparisons.
* @param {Array} [stackA=[]] Tracks traversed `value` objects.
* @param {Array} [stackB=[]] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, equalFunc, customizer, isWhere, stackA, stackB) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = objToString.call(object);
if (objTag == argsTag) {
objTag = objectTag;
} else if (objTag != objectTag) {
objIsArr = isTypedArray(object);
}
}
if (!othIsArr) {
othTag = objToString.call(other);
if (othTag == argsTag) {
othTag = objectTag;
} else if (othTag != objectTag) {
othIsArr = isTypedArray(other);
}
}
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && !(objIsArr || objIsObj)) {
return equalByTag(object, other, objTag);
}
var valWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (valWrapped || othWrapped) {
return equalFunc(valWrapped ? object.value() : object, othWrapped ? other.value() : other, customizer, isWhere, stackA, stackB);
}
if (!isSameTag) {
return false;
}
// Assume cyclic values are equal.
// For more information on detecting circular references see https://es5.github.io/#JO.
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == object) {
return stackB[length] == other;
}
}
// Add `object` and `other` to the stack of traversed objects.
stackA.push(object);
stackB.push(other);
var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isWhere, stackA, stackB);
stackA.pop();
stackB.pop();
return result;
}
module.exports = baseIsEqualDeep;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 1 2 1 | /**
* The base implementation of `_.isFunction` without support for environments
* with incorrect `typeof` results.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
*/
function baseIsFunction(value) {
// Avoid a Chakra JIT bug in compatibility modes of IE 11.
// See https://github.com/jashkenas/underscore/issues/1621 for more details.
return typeof value == 'function' || false;
}
module.exports = baseIsFunction;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | 1 1 1 1 1 | var baseIsEqual = require('./baseIsEqual');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.isMatch` without support for callback
* shorthands or `this` binding.
*
* @private
* @param {Object} object The object to inspect.
* @param {Array} props The source property names to match.
* @param {Array} values The source values to match.
* @param {Array} strictCompareFlags Strict comparison flags for source values.
* @param {Function} [customizer] The function to customize comparing objects.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, props, values, strictCompareFlags, customizer) {
var length = props.length;
if (object == null) {
return !length;
}
var index = -1,
noCustomizer = !customizer;
while (++index < length) {
if ((noCustomizer && strictCompareFlags[index])
? values[index] !== object[props[index]]
: !hasOwnProperty.call(object, props[index])
) {
return false;
}
}
index = -1;
while (++index < length) {
var key = props[index];
if (noCustomizer && strictCompareFlags[index]) {
var result = hasOwnProperty.call(object, key);
} else {
var objValue = object[key],
srcValue = values[index];
result = customizer ? customizer(objValue, srcValue, key) : undefined;
if (typeof result == 'undefined') {
result = baseIsEqual(srcValue, objValue, customizer, true);
}
}
if (!result) {
return false;
}
}
return true;
}
module.exports = baseIsMatch;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 1 1 1 1 1 | var baseIsMatch = require('./baseIsMatch'),
isStrictComparable = require('./isStrictComparable'),
keys = require('../object/keys');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* The base implementation of `_.matches` which does not clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new function.
*/
function baseMatches(source) {
var props = keys(source),
length = props.length;
if (length == 1) {
var key = props[0],
value = source[key];
if (isStrictComparable(value)) {
return function(object) {
return object != null && object[key] === value && hasOwnProperty.call(object, key);
};
}
}
var values = Array(length),
strictCompareFlags = Array(length);
while (length--) {
value = source[props[length]];
values[length] = value;
strictCompareFlags[length] = isStrictComparable(value);
}
return function(object) {
return baseIsMatch(object, props, values, strictCompareFlags);
};
}
module.exports = baseMatches;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 1 1 1 | var baseIsEqual = require('./baseIsEqual'),
isStrictComparable = require('./isStrictComparable');
/**
* The base implementation of `_.matchesProperty` which does not coerce `key`
* to a string.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} value The value to compare.
* @returns {Function} Returns the new function.
*/
function baseMatchesProperty(key, value) {
if (isStrictComparable(value)) {
return function(object) {
return object != null && object[key] === value;
};
}
return function(object) {
return object != null && baseIsEqual(value, object[key], null, true);
};
}
module.exports = baseMatchesProperty;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 1 1 | /**
* The base implementation of `_.property` which does not coerce `key` to a string.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
module.exports = baseProperty;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 1 1 1 | var identity = require('../utility/identity'),
metaMap = require('./metaMap');
/**
* The base implementation of `setData` without support for hot loop detection.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
module.exports = baseSetData;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 1 1 1 1 | /**
* Converts `value` to a string if it is not one. An empty string is returned
* for `null` or `undefined` values.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
Iif (typeof value == 'string') {
return value;
}
return value == null ? '' : (value + '');
}
module.exports = baseToString;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 1 1 1 | var identity = require('../utility/identity');
/**
* A specialized version of `baseCallback` which only supports `this` binding
* and specifying the number of arguments to provide to `func`.
*
* @private
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
function bindCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
if (typeof thisArg == 'undefined') {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 3: return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
case 5: return function(value, other, key, object, source) {
return func.call(thisArg, value, other, key, object, source);
};
}
return function() {
return func.apply(thisArg, arguments);
};
}
module.exports = bindCallback;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | 1 1 1 1 | var bindCallback = require('./bindCallback'),
isIterateeCall = require('./isIterateeCall');
/**
* Creates a function that assigns properties of source object(s) to a given
* destination object.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return function() {
var args = arguments,
length = args.length,
object = args[0];
if (length < 2 || object == null) {
return object;
}
var customizer = args[length - 2],
thisArg = args[length - 1],
guard = args[3];
if (length > 3 && typeof customizer == 'function') {
customizer = bindCallback(customizer, thisArg, 5);
length -= 2;
} else {
customizer = (length > 2 && typeof thisArg == 'function') ? thisArg : null;
length -= (customizer ? 1 : 0);
}
if (guard && isIterateeCall(args[1], args[2], guard)) {
customizer = length == 3 ? null : customizer;
length = 2;
}
var index = 0;
while (++index < length) {
var source = args[index];
if (source) {
assigner(object, source, customizer);
}
}
return object;
};
}
module.exports = createAssigner;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | 1 1 | /**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing arrays.
* @param {boolean} [isWhere] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, equalFunc, customizer, isWhere, stackA, stackB) {
var index = -1,
arrLength = array.length,
othLength = other.length,
result = true;
if (arrLength != othLength && !(isWhere && othLength > arrLength)) {
return false;
}
// Deep compare the contents, ignoring non-numeric properties.
while (result && ++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
result = undefined;
if (customizer) {
result = isWhere
? customizer(othValue, arrValue, index)
: customizer(arrValue, othValue, index);
}
if (typeof result == 'undefined') {
// Recursively compare arrays (susceptible to call stack limits).
if (isWhere) {
var othIndex = othLength;
while (othIndex--) {
othValue = other[othIndex];
result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isWhere, stackA, stackB);
if (result) {
break;
}
}
} else {
result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isWhere, stackA, stackB);
}
}
}
return !!result;
}
module.exports = equalArrays;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 1 1 1 | /** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
stringTag = '[object String]';
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} value The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag) {
switch (tag) {
case boolTag:
case dateTag:
// Coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
return +object == +other;
case errorTag:
return object.name == other.name && object.message == other.message;
case numberTag:
// Treat `NaN` vs. `NaN` as equal.
return (object != +object)
? other != +other
// But, treat `-0` vs. `+0` as not equal.
: (object == 0 ? ((1 / object) == (1 / other)) : object == +other);
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings primitives and string
// objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
return object == (other + '');
}
return false;
}
module.exports = equalByTag;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | 1 1 1 1 1 | var keys = require('../object/keys');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing values.
* @param {boolean} [isWhere] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, equalFunc, customizer, isWhere, stackA, stackB) {
var objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength != othLength && !isWhere) {
return false;
}
var hasCtor,
index = -1;
while (++index < objLength) {
var key = objProps[index],
result = hasOwnProperty.call(other, key);
if (result) {
var objValue = object[key],
othValue = other[key];
result = undefined;
if (customizer) {
result = isWhere
? customizer(othValue, objValue, key)
: customizer(objValue, othValue, key);
}
if (typeof result == 'undefined') {
// Recursively compare objects (susceptible to call stack limits).
result = (objValue && objValue === othValue) || equalFunc(objValue, othValue, customizer, isWhere, stackA, stackB);
}
}
if (!result) {
return false;
}
hasCtor || (hasCtor = key == 'constructor');
}
if (!hasCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
return false;
}
}
return true;
}
module.exports = equalObjects;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 1 1 1 1 1 1 | var baseSetData = require('./baseSetData'),
isNative = require('../lang/isNative'),
support = require('../support');
/** Used to detect named functions. */
var reFuncName = /^\s*function[ \n\r\t]+\w/;
/** Used to detect functions containing a `this` reference. */
var reThis = /\bthis\b/;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/**
* Checks if `func` is eligible for `this` binding.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is eligible, else `false`.
*/
function isBindable(func) {
var result = !(support.funcNames ? func.name : support.funcDecomp);
if (!result) {
var source = fnToString.call(func);
if (!support.funcNames) {
result = !reFuncName.test(source);
}
if (!result) {
// Check if `func` references the `this` keyword and store the result.
result = reThis.test(source) || isNative(func);
baseSetData(func, result);
}
}
return result;
}
module.exports = isBindable;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 1 1 1 | /**
* Used as the maximum length of an array-like value.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* for more details.
*/
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = +value;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
module.exports = isIndex;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 1 1 1 | var isIndex = require('./isIndex'),
isLength = require('./isLength'),
isObject = require('../lang/isObject');
/**
* Checks if the provided arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number') {
var length = object.length,
prereq = isLength(length) && isIndex(index, length);
} else {
prereq = type == 'string' && index in object;
}
if (prereq) {
var other = object[index];
return value === value ? (value === other) : (other !== other);
}
return false;
}
module.exports = isIterateeCall;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 1 1 1 | /**
* Used as the maximum length of an array-like value.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* for more details.
*/
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on ES `ToLength`. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength)
* for more details.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 1 1 | /**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return (value && typeof value == 'object') || false;
}
module.exports = isObjectLike;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 1 1 1 | var isObject = require('../lang/isObject');
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && (value === 0 ? ((1 / value) > 0) : !isObject(value));
}
module.exports = isStrictComparable;
|
| 1 2 3 4 5 6 7 8 9 10 11 | 1 1 1 1 | var isNative = require('../lang/isNative');
/** Native method references. */
var WeakMap = isNative(WeakMap = global.WeakMap) && WeakMap;
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
module.exports = metaMap;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 1 1 1 1 1 | var isArguments = require('../lang/isArguments'),
isArray = require('../lang/isArray'),
isIndex = require('./isIndex'),
isLength = require('./isLength'),
keysIn = require('../object/keysIn'),
support = require('../support');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A fallback implementation of `Object.keys` which creates an array of the
* own enumerable property names of `object`.
*
* @private
* @param {Object} object The object to inspect.
* @returns {Array} Returns the array of property names.
*/
function shimKeys(object) {
var props = keysIn(object),
propsLength = props.length,
length = propsLength && object.length;
var allowIndexes = length && isLength(length) &&
(isArray(object) || (support.nonEnumArgs && isArguments(object)));
var index = -1,
result = [];
while (++index < propsLength) {
var key = props[index];
if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
}
module.exports = shimKeys;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 1 1 1 | var isObject = require('../lang/isObject');
/**
* Converts `value` to an object if it is not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
return isObject(value) ? value : Object(value);
}
module.exports = toObject;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| isArguments.js | 75% | (6 / 8) | 0% | (0 / 5) | 0% | (0 / 1) | 75% | (6 / 8) | |
| isArray.js | 87.5% | (7 / 8) | 37.5% | (3 / 8) | 0% | (0 / 1) | 87.5% | (7 / 8) | |
| isEmpty.js | 33.33% | (3 / 9) | 0% | (0 / 10) | 0% | (0 / 1) | 33.33% | (3 / 9) | |
| isFunction.js | 87.5% | (7 / 8) | 85.71% | (6 / 7) | 0% | (0 / 1) | 87.5% | (7 / 8) | |
| isNative.js | 92.86% | (13 / 14) | 42.86% | (3 / 7) | 100% | (1 / 1) | 92.86% | (13 / 14) | |
| isObject.js | 50% | (2 / 4) | 0% | (0 / 4) | 0% | (0 / 1) | 50% | (2 / 4) | |
| isString.js | 85.71% | (6 / 7) | 0% | (0 / 4) | 0% | (0 / 1) | 85.71% | (6 / 7) | |
| isTypedArray.js | 90.91% | (10 / 11) | 0% | (0 / 4) | 0% | (0 / 1) | 90.91% | (10 / 11) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 1 1 1 1 1 1 | var isLength = require('../internal/isLength'),
isObjectLike = require('../internal/isObjectLike');
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the `toStringTag` of values.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* for more details.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as an `arguments` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
var length = isObjectLike(value) ? value.length : undefined;
return (isLength(length) && objToString.call(value) == argsTag) || false;
}
module.exports = isArguments;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 1 1 1 1 1 1 1 | var isLength = require('../internal/isLength'),
isNative = require('./isNative'),
isObjectLike = require('../internal/isObjectLike');
/** `Object#toString` result references. */
var arrayTag = '[object Array]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the `toStringTag` of values.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* for more details.
*/
var objToString = objectProto.toString;
/* Native method references for those with the same name as other `lodash` methods. */
var nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray;
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(function() { return arguments; }());
* // => false
*/
var isArray = nativeIsArray || function(value) {
return (isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag) || false;
};
module.exports = isArray;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 1 1 1 | var isArguments = require('./isArguments'),
isArray = require('./isArray'),
isFunction = require('./isFunction'),
isLength = require('../internal/isLength'),
isObjectLike = require('../internal/isObjectLike'),
isString = require('./isString'),
keys = require('../object/keys');
/**
* Checks if `value` is empty. A value is considered empty unless it is an
* `arguments` object, array, string, or jQuery-like collection with a length
* greater than `0` or an object with own enumerable properties.
*
* @static
* @memberOf _
* @category Lang
* @param {Array|Object|string} value The value to inspect.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
var length = value.length;
if (isLength(length) && (isArray(value) || isString(value) || isArguments(value) ||
(isObjectLike(value) && isFunction(value.splice)))) {
return !length;
}
return !keys(value).length;
}
module.exports = isEmpty;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 1 1 1 1 1 1 1 | var baseIsFunction = require('../internal/baseIsFunction'),
isNative = require('./isNative');
/** `Object#toString` result references. */
var funcTag = '[object Function]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the `toStringTag` of values.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* for more details.
*/
var objToString = objectProto.toString;
/** Native method references. */
var Uint8Array = isNative(Uint8Array = global.Uint8Array) && Uint8Array;
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
var isFunction = !(baseIsFunction(/x/) || (Uint8Array && !baseIsFunction(Uint8Array))) ? baseIsFunction : function(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 equivalents which return 'object' for typed array constructors.
return objToString.call(value) == funcTag;
};
module.exports = isFunction;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | 1 1 1 1 1 1 1 1 5 1 4 4 1 | var escapeRegExp = require('../string/escapeRegExp'),
isObjectLike = require('../internal/isObjectLike');
/** `Object#toString` result references. */
var funcTag = '[object Function]';
/** Used to detect host constructors (Safari > 5). */
var reHostCtor = /^\[object .+?Constructor\]$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/**
* Used to resolve the `toStringTag` of values.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* for more details.
*/
var objToString = objectProto.toString;
/** Used to detect if a method is native. */
var reNative = RegExp('^' +
escapeRegExp(objToString)
.replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
Eif (objToString.call(value) == funcTag) {
return reNative.test(fnToString.call(value));
}
return (isObjectLike(value) && reHostCtor.test(value)) || false;
}
module.exports = isNative;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 1 1 | /**
* Checks if `value` is the language type of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* **Note:** See the [ES5 spec](https://es5.github.io/#x8) for more details.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return type == 'function' || (value && type == 'object') || false;
}
module.exports = isObject;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | 1 1 1 1 1 1 | var isObjectLike = require('../internal/isObjectLike');
/** `Object#toString` result references. */
var stringTag = '[object String]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the `toStringTag` of values.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* for more details.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag) || false;
}
module.exports = isString;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | 1 1 1 1 1 1 1 1 1 1 | var isLength = require('../internal/isLength'),
isObjectLike = require('../internal/isObjectLike');
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dateTag] = typedArrayTags[errorTag] =
typedArrayTags[funcTag] = typedArrayTags[mapTag] =
typedArrayTags[numberTag] = typedArrayTags[objectTag] =
typedArrayTags[regexpTag] = typedArrayTags[setTag] =
typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the `toStringTag` of values.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* for more details.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
function isTypedArray(value) {
return (isObjectLike(value) && isLength(value.length) && typedArrayTags[objToString.call(value)]) || false;
}
module.exports = isTypedArray;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 1 1 1 | var baseAssign = require('../internal/baseAssign'),
createAssigner = require('../internal/createAssigner');
/**
* Assigns own enumerable properties of source object(s) to the destination
* object. Subsequent sources overwrite property assignments of previous sources.
* If `customizer` is provided it is invoked to produce the assigned values.
* The `customizer` is bound to `thisArg` and invoked with five arguments;
* (objectValue, sourceValue, key, object, source).
*
* @static
* @memberOf _
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @param {Function} [customizer] The function to customize assigning values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
* _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
* // => { 'user': 'fred', 'age': 40 }
*
* // using a customizer callback
* var defaults = _.partialRight(_.assign, function(value, other) {
* return typeof value == 'undefined' ? other : value;
* });
*
* defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
* // => { 'user': 'barney', 'age': 36 }
*/
var assign = createAssigner(baseAssign);
module.exports = assign;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 1 1 1 | var baseCopy = require('../internal/baseCopy'),
baseCreate = require('../internal/baseCreate'),
isIterateeCall = require('../internal/isIterateeCall'),
keys = require('./keys');
/**
* Creates an object that inherits from the given `prototype` object. If a
* `properties` object is provided its own enumerable properties are assigned
* to the created object.
*
* @static
* @memberOf _
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, {
* 'constructor': Circle
* });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/
function create(prototype, properties, guard) {
var result = baseCreate(prototype);
if (guard && isIterateeCall(prototype, properties, guard)) {
properties = null;
}
return properties ? baseCopy(properties, result, keys(properties)) : result;
}
module.exports = create;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 1 1 1 1 | var isLength = require('../internal/isLength'),
isNative = require('../lang/isNative'),
isObject = require('../lang/isObject'),
shimKeys = require('../internal/shimKeys');
/* Native method references for those with the same name as other `lodash` methods. */
var nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys;
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys)
* for more details.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
var keys = !nativeKeys ? shimKeys : function(object) {
if (object) {
var Ctor = object.constructor,
length = object.length;
}
if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
(typeof object != 'function' && (length && isLength(length)))) {
return shimKeys(object);
}
return isObject(object) ? nativeKeys(object) : [];
};
module.exports = keys;
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | 1 1 1 1 1 | var isArguments = require('../lang/isArguments'),
isArray = require('../lang/isArray'),
isIndex = require('../internal/isIndex'),
isLength = require('../internal/isLength'),
isObject = require('../lang/isObject'),
support = require('../support');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
if (object == null) {
return [];
}
if (!isObject(object)) {
object = Object(object);
}
var length = object.length;
length = (length && isLength(length) &&
(isArray(object) || (support.nonEnumArgs && isArguments(object))) && length) || 0;
var Ctor = object.constructor,
index = -1,
isProto = typeof Ctor == 'function' && Ctor.prototype === object,
result = Array(length),
skipIndexes = length > 0;
while (++index < length) {
result[index] = (index + '');
}
for (var key in object) {
if (!(skipIndexes && isIndex(key, length)) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = keysIn;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| escapeRegExp.js | 100% | (6 / 6) | 75% | (3 / 4) | 100% | (1 / 1) | 100% | (6 / 6) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 1 1 1 1 1 1 | var baseToString = require('../internal/baseToString');
/**
* Used to match `RegExp` special characters.
* See this [article on `RegExp` characters](http://www.regular-expressions.info/characters.html#special)
* for more details.
*/
var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g,
reHasRegExpChars = RegExp(reRegExpChars.source);
/**
* Escapes the `RegExp` special characters "\", "^", "$", ".", "|", "?", "*",
* "+", "(", ")", "[", "]", "{" and "}" in `string`.
*
* @static
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https://lodash\.com/\)'
*/
function escapeRegExp(string) {
string = baseToString(string);
return (string && reHasRegExpChars.test(string))
? string.replace(reRegExpChars, '\\$&')
: string;
}
module.exports = escapeRegExp;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| identity.js | 66.67% | (2 / 3) | 100% | (0 / 0) | 0% | (0 / 1) | 66.67% | (2 / 3) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 1 1 | /**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utility
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
*
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| sax.js | 10.64% | (81 / 761) | 1.8% | (8 / 445) | 9.62% | (5 / 52) | 10.8% | (81 / 750) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 17 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 5 73 73 1 1 1 1 1 1 1 1 253 253 253 1 36 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | ;(function (sax) { // wrapper for non-node envs
sax.parser = function (strict, opt) { return new SAXParser(strict, opt) }
sax.SAXParser = SAXParser
sax.SAXStream = SAXStream
sax.createStream = createStream
// When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns.
// When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)),
// since that's the earliest that a buffer overrun could occur. This way, checks are
// as rare as required, but as often as necessary to ensure never crossing this bound.
// Furthermore, buffers are only tested at most once per write(), so passing a very
// large string into write() might have undesirable effects, but this is manageable by
// the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme
// edge case, result in creating at most one complete copy of the string passed in.
// Set to Infinity to have unlimited buffers.
sax.MAX_BUFFER_LENGTH = 64 * 1024
var buffers = [
'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype',
'procInstName', 'procInstBody', 'entity', 'attribName',
'attribValue', 'cdata', 'script'
]
sax.EVENTS = [
'text',
'processinginstruction',
'sgmldeclaration',
'doctype',
'comment',
'attribute',
'opentag',
'closetag',
'opencdata',
'cdata',
'closecdata',
'error',
'end',
'ready',
'script',
'opennamespace',
'closenamespace'
]
function SAXParser (strict, opt) {
if (!(this instanceof SAXParser)) {
return new SAXParser(strict, opt)
}
var parser = this
clearBuffers(parser)
parser.q = parser.c = ''
parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH
parser.opt = opt || {}
parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags
parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase'
parser.tags = []
parser.closed = parser.closedRoot = parser.sawRoot = false
parser.tag = parser.error = null
parser.strict = !!strict
parser.noscript = !!(strict || parser.opt.noscript)
parser.state = S.BEGIN
parser.strictEntities = parser.opt.strictEntities
parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES)
parser.attribList = []
// namespaces form a prototype chain.
// it always points at the current tag,
// which protos to its parent tag.
if (parser.opt.xmlns) {
parser.ns = Object.create(rootNS)
}
// mostly just for error reporting
parser.trackPosition = parser.opt.position !== false
if (parser.trackPosition) {
parser.position = parser.line = parser.column = 0
}
emit(parser, 'onready')
}
Iif (!Object.create) {
Object.create = function (o) {
function F () {}
F.prototype = o
var newf = new F()
return newf
}
}
Iif (!Object.keys) {
Object.keys = function (o) {
var a = []
for (var i in o) if (o.hasOwnProperty(i)) a.push(i)
return a
}
}
function checkBufferLength (parser) {
var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10)
var maxActual = 0
for (var i = 0, l = buffers.length; i < l; i++) {
var len = parser[buffers[i]].length
if (len > maxAllowed) {
// Text/cdata nodes can get big, and since they're buffered,
// we can get here under normal conditions.
// Avoid issues by emitting the text node now,
// so at least it won't get any bigger.
switch (buffers[i]) {
case 'textNode':
closeText(parser)
break
case 'cdata':
emitNode(parser, 'oncdata', parser.cdata)
parser.cdata = ''
break
case 'script':
emitNode(parser, 'onscript', parser.script)
parser.script = ''
break
default:
error(parser, 'Max buffer length exceeded: ' + buffers[i])
}
}
maxActual = Math.max(maxActual, len)
}
// schedule the next check for the earliest possible buffer overrun.
var m = sax.MAX_BUFFER_LENGTH - maxActual
parser.bufferCheckPosition = m + parser.position
}
function clearBuffers (parser) {
for (var i = 0, l = buffers.length; i < l; i++) {
parser[buffers[i]] = ''
}
}
function flushBuffers (parser) {
closeText(parser)
if (parser.cdata !== '') {
emitNode(parser, 'oncdata', parser.cdata)
parser.cdata = ''
}
if (parser.script !== '') {
emitNode(parser, 'onscript', parser.script)
parser.script = ''
}
}
SAXParser.prototype = {
end: function () { end(this) },
write: write,
resume: function () { this.error = null; return this },
close: function () { return this.write(null) },
flush: function () { flushBuffers(this) }
}
var Stream
try {
Stream = require('stream').Stream
} catch (ex) {
Stream = function () {}
}
var streamWraps = sax.EVENTS.filter(function (ev) {
return ev !== 'error' && ev !== 'end'
})
function createStream (strict, opt) {
return new SAXStream(strict, opt)
}
function SAXStream (strict, opt) {
if (!(this instanceof SAXStream)) {
return new SAXStream(strict, opt)
}
Stream.apply(this)
this._parser = new SAXParser(strict, opt)
this.writable = true
this.readable = true
var me = this
this._parser.onend = function () {
me.emit('end')
}
this._parser.onerror = function (er) {
me.emit('error', er)
// if didn't throw, then means error was handled.
// go ahead and clear error, so we can write again.
me._parser.error = null
}
this._decoder = null
streamWraps.forEach(function (ev) {
Object.defineProperty(me, 'on' + ev, {
get: function () {
return me._parser['on' + ev]
},
set: function (h) {
if (!h) {
me.removeAllListeners(ev)
me._parser['on' + ev] = h
return h
}
me.on(ev, h)
},
enumerable: true,
configurable: false
})
})
}
SAXStream.prototype = Object.create(Stream.prototype, {
constructor: {
value: SAXStream
}
})
SAXStream.prototype.write = function (data) {
if (typeof Buffer === 'function' &&
typeof Buffer.isBuffer === 'function' &&
Buffer.isBuffer(data)) {
if (!this._decoder) {
var SD = require('string_decoder').StringDecoder
this._decoder = new SD('utf8')
}
data = this._decoder.write(data)
}
this._parser.write(data.toString())
this.emit('data', data)
return true
}
SAXStream.prototype.end = function (chunk) {
if (chunk && chunk.length) {
this.write(chunk)
}
this._parser.end()
return true
}
SAXStream.prototype.on = function (ev, handler) {
var me = this
if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) {
me._parser['on' + ev] = function () {
var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)
args.splice(0, 0, ev)
me.emit.apply(me, args)
}
}
return Stream.prototype.on.call(me, ev, handler)
}
// character classes and tokens
var whitespace = '\r\n\t '
// this really needs to be replaced with character classes.
// XML allows all manner of ridiculous numbers and digits.
var number = '0124356789'
var letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
// (Letter | "_" | ":")
var quote = '\'"'
var attribEnd = whitespace + '>'
var CDATA = '[CDATA['
var DOCTYPE = 'DOCTYPE'
var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'
var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/'
var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }
// turn all the string character sets into character class objects.
whitespace = charClass(whitespace)
number = charClass(number)
letter = charClass(letter)
// http://www.w3.org/TR/REC-xml/#NT-NameStartChar
// This implementation works on strings, a single character at a time
// as such, it cannot ever support astral-plane characters (10000-EFFFF)
// without a significant breaking change to either this parser, or the
// JavaScript language. Implementation of an emoji-capable xml parser
// is left as an exercise for the reader.
var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/
var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040\.\d-]/
var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/
var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040\.\d-]/
quote = charClass(quote)
attribEnd = charClass(attribEnd)
function charClass (str) {
return str.split('').reduce(function (s, c) {
s[c] = true
return s
}, {})
}
function isRegExp (c) {
return Object.prototype.toString.call(c) === '[object RegExp]'
}
function is (charclass, c) {
return isRegExp(charclass) ? !!c.match(charclass) : charclass[c]
}
function not (charclass, c) {
return !is(charclass, c)
}
var S = 0
sax.STATE = {
BEGIN: S++, // leading byte order mark or whitespace
BEGIN_WHITESPACE: S++, // leading whitespace
TEXT: S++, // general stuff
TEXT_ENTITY: S++, // & and such.
OPEN_WAKA: S++, // <
SGML_DECL: S++, // <!BLARG
SGML_DECL_QUOTED: S++, // <!BLARG foo "bar
DOCTYPE: S++, // <!DOCTYPE
DOCTYPE_QUOTED: S++, // <!DOCTYPE "//blah
DOCTYPE_DTD: S++, // <!DOCTYPE "//blah" [ ...
DOCTYPE_DTD_QUOTED: S++, // <!DOCTYPE "//blah" [ "foo
COMMENT_STARTING: S++, // <!-
COMMENT: S++, // <!--
COMMENT_ENDING: S++, // <!-- blah -
COMMENT_ENDED: S++, // <!-- blah --
CDATA: S++, // <![CDATA[ something
CDATA_ENDING: S++, // ]
CDATA_ENDING_2: S++, // ]]
PROC_INST: S++, // <?hi
PROC_INST_BODY: S++, // <?hi there
PROC_INST_ENDING: S++, // <?hi "there" ?
OPEN_TAG: S++, // <strong
OPEN_TAG_SLASH: S++, // <strong /
ATTRIB: S++, // <a
ATTRIB_NAME: S++, // <a foo
ATTRIB_NAME_SAW_WHITE: S++, // <a foo _
ATTRIB_VALUE: S++, // <a foo=
ATTRIB_VALUE_QUOTED: S++, // <a foo="bar
ATTRIB_VALUE_CLOSED: S++, // <a foo="bar"
ATTRIB_VALUE_UNQUOTED: S++, // <a foo=bar
ATTRIB_VALUE_ENTITY_Q: S++, // <foo bar="""
ATTRIB_VALUE_ENTITY_U: S++, // <foo bar="
CLOSE_TAG: S++, // </a
CLOSE_TAG_SAW_WHITE: S++, // </a >
SCRIPT: S++, // <script> ...
SCRIPT_ENDING: S++ // <script> ... <
}
sax.XML_ENTITIES = {
'amp': '&',
'gt': '>',
'lt': '<',
'quot': '"',
'apos': "'"
}
sax.ENTITIES = {
'amp': '&',
'gt': '>',
'lt': '<',
'quot': '"',
'apos': "'",
'AElig': 198,
'Aacute': 193,
'Acirc': 194,
'Agrave': 192,
'Aring': 197,
'Atilde': 195,
'Auml': 196,
'Ccedil': 199,
'ETH': 208,
'Eacute': 201,
'Ecirc': 202,
'Egrave': 200,
'Euml': 203,
'Iacute': 205,
'Icirc': 206,
'Igrave': 204,
'Iuml': 207,
'Ntilde': 209,
'Oacute': 211,
'Ocirc': 212,
'Ograve': 210,
'Oslash': 216,
'Otilde': 213,
'Ouml': 214,
'THORN': 222,
'Uacute': 218,
'Ucirc': 219,
'Ugrave': 217,
'Uuml': 220,
'Yacute': 221,
'aacute': 225,
'acirc': 226,
'aelig': 230,
'agrave': 224,
'aring': 229,
'atilde': 227,
'auml': 228,
'ccedil': 231,
'eacute': 233,
'ecirc': 234,
'egrave': 232,
'eth': 240,
'euml': 235,
'iacute': 237,
'icirc': 238,
'igrave': 236,
'iuml': 239,
'ntilde': 241,
'oacute': 243,
'ocirc': 244,
'ograve': 242,
'oslash': 248,
'otilde': 245,
'ouml': 246,
'szlig': 223,
'thorn': 254,
'uacute': 250,
'ucirc': 251,
'ugrave': 249,
'uuml': 252,
'yacute': 253,
'yuml': 255,
'copy': 169,
'reg': 174,
'nbsp': 160,
'iexcl': 161,
'cent': 162,
'pound': 163,
'curren': 164,
'yen': 165,
'brvbar': 166,
'sect': 167,
'uml': 168,
'ordf': 170,
'laquo': 171,
'not': 172,
'shy': 173,
'macr': 175,
'deg': 176,
'plusmn': 177,
'sup1': 185,
'sup2': 178,
'sup3': 179,
'acute': 180,
'micro': 181,
'para': 182,
'middot': 183,
'cedil': 184,
'ordm': 186,
'raquo': 187,
'frac14': 188,
'frac12': 189,
'frac34': 190,
'iquest': 191,
'times': 215,
'divide': 247,
'OElig': 338,
'oelig': 339,
'Scaron': 352,
'scaron': 353,
'Yuml': 376,
'fnof': 402,
'circ': 710,
'tilde': 732,
'Alpha': 913,
'Beta': 914,
'Gamma': 915,
'Delta': 916,
'Epsilon': 917,
'Zeta': 918,
'Eta': 919,
'Theta': 920,
'Iota': 921,
'Kappa': 922,
'Lambda': 923,
'Mu': 924,
'Nu': 925,
'Xi': 926,
'Omicron': 927,
'Pi': 928,
'Rho': 929,
'Sigma': 931,
'Tau': 932,
'Upsilon': 933,
'Phi': 934,
'Chi': 935,
'Psi': 936,
'Omega': 937,
'alpha': 945,
'beta': 946,
'gamma': 947,
'delta': 948,
'epsilon': 949,
'zeta': 950,
'eta': 951,
'theta': 952,
'iota': 953,
'kappa': 954,
'lambda': 955,
'mu': 956,
'nu': 957,
'xi': 958,
'omicron': 959,
'pi': 960,
'rho': 961,
'sigmaf': 962,
'sigma': 963,
'tau': 964,
'upsilon': 965,
'phi': 966,
'chi': 967,
'psi': 968,
'omega': 969,
'thetasym': 977,
'upsih': 978,
'piv': 982,
'ensp': 8194,
'emsp': 8195,
'thinsp': 8201,
'zwnj': 8204,
'zwj': 8205,
'lrm': 8206,
'rlm': 8207,
'ndash': 8211,
'mdash': 8212,
'lsquo': 8216,
'rsquo': 8217,
'sbquo': 8218,
'ldquo': 8220,
'rdquo': 8221,
'bdquo': 8222,
'dagger': 8224,
'Dagger': 8225,
'bull': 8226,
'hellip': 8230,
'permil': 8240,
'prime': 8242,
'Prime': 8243,
'lsaquo': 8249,
'rsaquo': 8250,
'oline': 8254,
'frasl': 8260,
'euro': 8364,
'image': 8465,
'weierp': 8472,
'real': 8476,
'trade': 8482,
'alefsym': 8501,
'larr': 8592,
'uarr': 8593,
'rarr': 8594,
'darr': 8595,
'harr': 8596,
'crarr': 8629,
'lArr': 8656,
'uArr': 8657,
'rArr': 8658,
'dArr': 8659,
'hArr': 8660,
'forall': 8704,
'part': 8706,
'exist': 8707,
'empty': 8709,
'nabla': 8711,
'isin': 8712,
'notin': 8713,
'ni': 8715,
'prod': 8719,
'sum': 8721,
'minus': 8722,
'lowast': 8727,
'radic': 8730,
'prop': 8733,
'infin': 8734,
'ang': 8736,
'and': 8743,
'or': 8744,
'cap': 8745,
'cup': 8746,
'int': 8747,
'there4': 8756,
'sim': 8764,
'cong': 8773,
'asymp': 8776,
'ne': 8800,
'equiv': 8801,
'le': 8804,
'ge': 8805,
'sub': 8834,
'sup': 8835,
'nsub': 8836,
'sube': 8838,
'supe': 8839,
'oplus': 8853,
'otimes': 8855,
'perp': 8869,
'sdot': 8901,
'lceil': 8968,
'rceil': 8969,
'lfloor': 8970,
'rfloor': 8971,
'lang': 9001,
'rang': 9002,
'loz': 9674,
'spades': 9824,
'clubs': 9827,
'hearts': 9829,
'diams': 9830
}
Object.keys(sax.ENTITIES).forEach(function (key) {
var e = sax.ENTITIES[key]
var s = typeof e === 'number' ? String.fromCharCode(e) : e
sax.ENTITIES[key] = s
})
for (var s in sax.STATE) {
sax.STATE[sax.STATE[s]] = s
}
// shorthand
S = sax.STATE
function emit (parser, event, data) {
parser[event] && parser[event](data)
}
function emitNode (parser, nodeType, data) {
if (parser.textNode) closeText(parser)
emit(parser, nodeType, data)
}
function closeText (parser) {
parser.textNode = textopts(parser.opt, parser.textNode)
if (parser.textNode) emit(parser, 'ontext', parser.textNode)
parser.textNode = ''
}
function textopts (opt, text) {
if (opt.trim) text = text.trim()
if (opt.normalize) text = text.replace(/\s+/g, ' ')
return text
}
function error (parser, er) {
closeText(parser)
if (parser.trackPosition) {
er += '\nLine: ' + parser.line +
'\nColumn: ' + parser.column +
'\nChar: ' + parser.c
}
er = new Error(er)
parser.error = er
emit(parser, 'onerror', er)
return parser
}
function end (parser) {
if (parser.sawRoot && !parser.closedRoot) strictFail(parser, 'Unclosed root tag')
if ((parser.state !== S.BEGIN) &&
(parser.state !== S.BEGIN_WHITESPACE) &&
(parser.state !== S.TEXT)) {
error(parser, 'Unexpected end')
}
closeText(parser)
parser.c = ''
parser.closed = true
emit(parser, 'onend')
SAXParser.call(parser, parser.strict, parser.opt)
return parser
}
function strictFail (parser, message) {
if (typeof parser !== 'object' || !(parser instanceof SAXParser)) {
throw new Error('bad call to strictFail')
}
if (parser.strict) {
error(parser, message)
}
}
function newTag (parser) {
if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase]()
var parent = parser.tags[parser.tags.length - 1] || parser
var tag = parser.tag = { name: parser.tagName, attributes: {} }
// will be overridden if tag contails an xmlns="foo" or xmlns:foo="bar"
if (parser.opt.xmlns) {
tag.ns = parent.ns
}
parser.attribList.length = 0
}
function qname (name, attribute) {
var i = name.indexOf(':')
var qualName = i < 0 ? [ '', name ] : name.split(':')
var prefix = qualName[0]
var local = qualName[1]
// <x "xmlns"="http://foo">
if (attribute && name === 'xmlns') {
prefix = 'xmlns'
local = ''
}
return { prefix: prefix, local: local }
}
function attrib (parser) {
if (!parser.strict) {
parser.attribName = parser.attribName[parser.looseCase]()
}
if (parser.attribList.indexOf(parser.attribName) !== -1 ||
parser.tag.attributes.hasOwnProperty(parser.attribName)) {
parser.attribName = parser.attribValue = ''
return
}
if (parser.opt.xmlns) {
var qn = qname(parser.attribName, true)
var prefix = qn.prefix
var local = qn.local
if (prefix === 'xmlns') {
// namespace binding attribute. push the binding into scope
if (local === 'xml' && parser.attribValue !== XML_NAMESPACE) {
strictFail(parser,
'xml: prefix must be bound to ' + XML_NAMESPACE + '\n' +
'Actual: ' + parser.attribValue)
} else if (local === 'xmlns' && parser.attribValue !== XMLNS_NAMESPACE) {
strictFail(parser,
'xmlns: prefix must be bound to ' + XMLNS_NAMESPACE + '\n' +
'Actual: ' + parser.attribValue)
} else {
var tag = parser.tag
var parent = parser.tags[parser.tags.length - 1] || parser
if (tag.ns === parent.ns) {
tag.ns = Object.create(parent.ns)
}
tag.ns[local] = parser.attribValue
}
}
// defer onattribute events until all attributes have been seen
// so any new bindings can take effect. preserve attribute order
// so deferred events can be emitted in document order
parser.attribList.push([parser.attribName, parser.attribValue])
} else {
// in non-xmlns mode, we can emit the event right away
parser.tag.attributes[parser.attribName] = parser.attribValue
emitNode(parser, 'onattribute', {
name: parser.attribName,
value: parser.attribValue
})
}
parser.attribName = parser.attribValue = ''
}
function openTag (parser, selfClosing) {
if (parser.opt.xmlns) {
// emit namespace binding events
var tag = parser.tag
// add namespace info to tag
var qn = qname(parser.tagName)
tag.prefix = qn.prefix
tag.local = qn.local
tag.uri = tag.ns[qn.prefix] || ''
if (tag.prefix && !tag.uri) {
strictFail(parser, 'Unbound namespace prefix: ' +
JSON.stringify(parser.tagName))
tag.uri = qn.prefix
}
var parent = parser.tags[parser.tags.length - 1] || parser
if (tag.ns && parent.ns !== tag.ns) {
Object.keys(tag.ns).forEach(function (p) {
emitNode(parser, 'onopennamespace', {
prefix: p,
uri: tag.ns[p]
})
})
}
// handle deferred onattribute events
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (var i = 0, l = parser.attribList.length; i < l; i++) {
var nv = parser.attribList[i]
var name = nv[0]
var value = nv[1]
var qualName = qname(name, true)
var prefix = qualName.prefix
var local = qualName.local
var uri = prefix === '' ? '' : (tag.ns[prefix] || '')
var a = {
name: name,
value: value,
prefix: prefix,
local: local,
uri: uri
}
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (prefix && prefix !== 'xmlns' && !uri) {
strictFail(parser, 'Unbound namespace prefix: ' +
JSON.stringify(prefix))
a.uri = prefix
}
parser.tag.attributes[name] = a
emitNode(parser, 'onattribute', a)
}
parser.attribList.length = 0
}
parser.tag.isSelfClosing = !!selfClosing
// process the tag
parser.sawRoot = true
parser.tags.push(parser.tag)
emitNode(parser, 'onopentag', parser.tag)
if (!selfClosing) {
// special case for <script> in non-strict mode.
if (!parser.noscript && parser.tagName.toLowerCase() === 'script') {
parser.state = S.SCRIPT
} else {
parser.state = S.TEXT
}
parser.tag = null
parser.tagName = ''
}
parser.attribName = parser.attribValue = ''
parser.attribList.length = 0
}
function closeTag (parser) {
if (!parser.tagName) {
strictFail(parser, 'Weird empty close tag.')
parser.textNode += '</>'
parser.state = S.TEXT
return
}
if (parser.script) {
if (parser.tagName !== 'script') {
parser.script += '</' + parser.tagName + '>'
parser.tagName = ''
parser.state = S.SCRIPT
return
}
emitNode(parser, 'onscript', parser.script)
parser.script = ''
}
// first make sure that the closing tag actually exists.
// <a><b></c></b></a> will close everything, otherwise.
var t = parser.tags.length
var tagName = parser.tagName
if (!parser.strict) {
tagName = tagName[parser.looseCase]()
}
var closeTo = tagName
while (t--) {
var close = parser.tags[t]
if (close.name !== closeTo) {
// fail the first time in strict mode
strictFail(parser, 'Unexpected close tag')
} else {
break
}
}
// didn't find it. we already failed for strict, so just abort.
if (t < 0) {
strictFail(parser, 'Unmatched closing tag: ' + parser.tagName)
parser.textNode += '</' + parser.tagName + '>'
parser.state = S.TEXT
return
}
parser.tagName = tagName
var s = parser.tags.length
while (s-- > t) {
var tag = parser.tag = parser.tags.pop()
parser.tagName = parser.tag.name
emitNode(parser, 'onclosetag', parser.tagName)
var x = {}
for (var i in tag.ns) {
x[i] = tag.ns[i]
}
var parent = parser.tags[parser.tags.length - 1] || parser
if (parser.opt.xmlns && tag.ns !== parent.ns) {
// remove namespace bindings introduced by tag
Object.keys(tag.ns).forEach(function (p) {
var n = tag.ns[p]
emitNode(parser, 'onclosenamespace', { prefix: p, uri: n })
})
}
}
if (t === 0) parser.closedRoot = true
parser.tagName = parser.attribValue = parser.attribName = ''
parser.attribList.length = 0
parser.state = S.TEXT
}
function parseEntity (parser) {
var entity = parser.entity
var entityLC = entity.toLowerCase()
var num
var numStr = ''
if (parser.ENTITIES[entity]) {
return parser.ENTITIES[entity]
}
if (parser.ENTITIES[entityLC]) {
return parser.ENTITIES[entityLC]
}
entity = entityLC
if (entity.charAt(0) === '#') {
if (entity.charAt(1) === 'x') {
entity = entity.slice(2)
num = parseInt(entity, 16)
numStr = num.toString(16)
} else {
entity = entity.slice(1)
num = parseInt(entity, 10)
numStr = num.toString(10)
}
}
entity = entity.replace(/^0+/, '')
if (numStr.toLowerCase() !== entity) {
strictFail(parser, 'Invalid character entity')
return '&' + parser.entity + ';'
}
return String.fromCodePoint(num)
}
function beginWhiteSpace (parser, c) {
if (c === '<') {
parser.state = S.OPEN_WAKA
parser.startTagPosition = parser.position
} else if (not(whitespace, c)) {
// have to process this as a text node.
// weird, but happens.
strictFail(parser, 'Non-whitespace before first tag.')
parser.textNode = c
parser.state = S.TEXT
}
}
function charAt (chunk, i) {
var result = ''
if (i < chunk.length) {
result = chunk.charAt(i)
}
return result
}
function write (chunk) {
var parser = this
if (this.error) {
throw this.error
}
if (parser.closed) {
return error(parser,
'Cannot write after close. Assign an onready handler.')
}
if (chunk === null) {
return end(parser)
}
var i = 0
var c = ''
while (true) {
c = charAt(chunk, i++)
parser.c = c
if (!c) {
break
}
if (parser.trackPosition) {
parser.position++
if (c === '\n') {
parser.line++
parser.column = 0
} else {
parser.column++
}
}
switch (parser.state) {
case S.BEGIN:
parser.state = S.BEGIN_WHITESPACE
if (c === '\uFEFF') {
continue
}
beginWhiteSpace(parser, c)
continue
case S.BEGIN_WHITESPACE:
beginWhiteSpace(parser, c)
continue
case S.TEXT:
if (parser.sawRoot && !parser.closedRoot) {
var starti = i - 1
while (c && c !== '<' && c !== '&') {
c = charAt(chunk, i++)
if (c && parser.trackPosition) {
parser.position++
if (c === '\n') {
parser.line++
parser.column = 0
} else {
parser.column++
}
}
}
parser.textNode += chunk.substring(starti, i - 1)
}
if (c === '<' && !(parser.sawRoot && parser.closedRoot && !parser.strict)) {
parser.state = S.OPEN_WAKA
parser.startTagPosition = parser.position
} else {
if (not(whitespace, c) && (!parser.sawRoot || parser.closedRoot)) {
strictFail(parser, 'Text data outside of root node.')
}
if (c === '&') {
parser.state = S.TEXT_ENTITY
} else {
parser.textNode += c
}
}
continue
case S.SCRIPT:
// only non-strict
if (c === '<') {
parser.state = S.SCRIPT_ENDING
} else {
parser.script += c
}
continue
case S.SCRIPT_ENDING:
if (c === '/') {
parser.state = S.CLOSE_TAG
} else {
parser.script += '<' + c
parser.state = S.SCRIPT
}
continue
case S.OPEN_WAKA:
// either a /, ?, !, or text is coming next.
if (c === '!') {
parser.state = S.SGML_DECL
parser.sgmlDecl = ''
} else if (is(whitespace, c)) {
// wait for it...
} else if (is(nameStart, c)) {
parser.state = S.OPEN_TAG
parser.tagName = c
} else if (c === '/') {
parser.state = S.CLOSE_TAG
parser.tagName = ''
} else if (c === '?') {
parser.state = S.PROC_INST
parser.procInstName = parser.procInstBody = ''
} else {
strictFail(parser, 'Unencoded <')
// if there was some whitespace, then add that in.
if (parser.startTagPosition + 1 < parser.position) {
var pad = parser.position - parser.startTagPosition
c = new Array(pad).join(' ') + c
}
parser.textNode += '<' + c
parser.state = S.TEXT
}
continue
case S.SGML_DECL:
if ((parser.sgmlDecl + c).toUpperCase() === CDATA) {
emitNode(parser, 'onopencdata')
parser.state = S.CDATA
parser.sgmlDecl = ''
parser.cdata = ''
} else if (parser.sgmlDecl + c === '--') {
parser.state = S.COMMENT
parser.comment = ''
parser.sgmlDecl = ''
} else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) {
parser.state = S.DOCTYPE
if (parser.doctype || parser.sawRoot) {
strictFail(parser,
'Inappropriately located doctype declaration')
}
parser.doctype = ''
parser.sgmlDecl = ''
} else if (c === '>') {
emitNode(parser, 'onsgmldeclaration', parser.sgmlDecl)
parser.sgmlDecl = ''
parser.state = S.TEXT
} else if (is(quote, c)) {
parser.state = S.SGML_DECL_QUOTED
parser.sgmlDecl += c
} else {
parser.sgmlDecl += c
}
continue
case S.SGML_DECL_QUOTED:
if (c === parser.q) {
parser.state = S.SGML_DECL
parser.q = ''
}
parser.sgmlDecl += c
continue
case S.DOCTYPE:
if (c === '>') {
parser.state = S.TEXT
emitNode(parser, 'ondoctype', parser.doctype)
parser.doctype = true // just remember that we saw it.
} else {
parser.doctype += c
if (c === '[') {
parser.state = S.DOCTYPE_DTD
} else if (is(quote, c)) {
parser.state = S.DOCTYPE_QUOTED
parser.q = c
}
}
continue
case S.DOCTYPE_QUOTED:
parser.doctype += c
if (c === parser.q) {
parser.q = ''
parser.state = S.DOCTYPE
}
continue
case S.DOCTYPE_DTD:
parser.doctype += c
if (c === ']') {
parser.state = S.DOCTYPE
} else if (is(quote, c)) {
parser.state = S.DOCTYPE_DTD_QUOTED
parser.q = c
}
continue
case S.DOCTYPE_DTD_QUOTED:
parser.doctype += c
if (c === parser.q) {
parser.state = S.DOCTYPE_DTD
parser.q = ''
}
continue
case S.COMMENT:
if (c === '-') {
parser.state = S.COMMENT_ENDING
} else {
parser.comment += c
}
continue
case S.COMMENT_ENDING:
if (c === '-') {
parser.state = S.COMMENT_ENDED
parser.comment = textopts(parser.opt, parser.comment)
if (parser.comment) {
emitNode(parser, 'oncomment', parser.comment)
}
parser.comment = ''
} else {
parser.comment += '-' + c
parser.state = S.COMMENT
}
continue
case S.COMMENT_ENDED:
if (c !== '>') {
strictFail(parser, 'Malformed comment')
// allow <!-- blah -- bloo --> in non-strict mode,
// which is a comment of " blah -- bloo "
parser.comment += '--' + c
parser.state = S.COMMENT
} else {
parser.state = S.TEXT
}
continue
case S.CDATA:
if (c === ']') {
parser.state = S.CDATA_ENDING
} else {
parser.cdata += c
}
continue
case S.CDATA_ENDING:
if (c === ']') {
parser.state = S.CDATA_ENDING_2
} else {
parser.cdata += ']' + c
parser.state = S.CDATA
}
continue
case S.CDATA_ENDING_2:
if (c === '>') {
if (parser.cdata) {
emitNode(parser, 'oncdata', parser.cdata)
}
emitNode(parser, 'onclosecdata')
parser.cdata = ''
parser.state = S.TEXT
} else if (c === ']') {
parser.cdata += ']'
} else {
parser.cdata += ']]' + c
parser.state = S.CDATA
}
continue
case S.PROC_INST:
if (c === '?') {
parser.state = S.PROC_INST_ENDING
} else if (is(whitespace, c)) {
parser.state = S.PROC_INST_BODY
} else {
parser.procInstName += c
}
continue
case S.PROC_INST_BODY:
if (!parser.procInstBody && is(whitespace, c)) {
continue
} else if (c === '?') {
parser.state = S.PROC_INST_ENDING
} else {
parser.procInstBody += c
}
continue
case S.PROC_INST_ENDING:
if (c === '>') {
emitNode(parser, 'onprocessinginstruction', {
name: parser.procInstName,
body: parser.procInstBody
})
parser.procInstName = parser.procInstBody = ''
parser.state = S.TEXT
} else {
parser.procInstBody += '?' + c
parser.state = S.PROC_INST_BODY
}
continue
case S.OPEN_TAG:
if (is(nameBody, c)) {
parser.tagName += c
} else {
newTag(parser)
if (c === '>') {
openTag(parser)
} else if (c === '/') {
parser.state = S.OPEN_TAG_SLASH
} else {
if (not(whitespace, c)) {
strictFail(parser, 'Invalid character in tag name')
}
parser.state = S.ATTRIB
}
}
continue
case S.OPEN_TAG_SLASH:
if (c === '>') {
openTag(parser, true)
closeTag(parser)
} else {
strictFail(parser, 'Forward-slash in opening tag not followed by >')
parser.state = S.ATTRIB
}
continue
case S.ATTRIB:
// haven't read the attribute name yet.
if (is(whitespace, c)) {
continue
} else if (c === '>') {
openTag(parser)
} else if (c === '/') {
parser.state = S.OPEN_TAG_SLASH
} else if (is(nameStart, c)) {
parser.attribName = c
parser.attribValue = ''
parser.state = S.ATTRIB_NAME
} else {
strictFail(parser, 'Invalid attribute name')
}
continue
case S.ATTRIB_NAME:
if (c === '=') {
parser.state = S.ATTRIB_VALUE
} else if (c === '>') {
strictFail(parser, 'Attribute without value')
parser.attribValue = parser.attribName
attrib(parser)
openTag(parser)
} else if (is(whitespace, c)) {
parser.state = S.ATTRIB_NAME_SAW_WHITE
} else if (is(nameBody, c)) {
parser.attribName += c
} else {
strictFail(parser, 'Invalid attribute name')
}
continue
case S.ATTRIB_NAME_SAW_WHITE:
if (c === '=') {
parser.state = S.ATTRIB_VALUE
} else if (is(whitespace, c)) {
continue
} else {
strictFail(parser, 'Attribute without value')
parser.tag.attributes[parser.attribName] = ''
parser.attribValue = ''
emitNode(parser, 'onattribute', {
name: parser.attribName,
value: ''
})
parser.attribName = ''
if (c === '>') {
openTag(parser)
} else if (is(nameStart, c)) {
parser.attribName = c
parser.state = S.ATTRIB_NAME
} else {
strictFail(parser, 'Invalid attribute name')
parser.state = S.ATTRIB
}
}
continue
case S.ATTRIB_VALUE:
if (is(whitespace, c)) {
continue
} else if (is(quote, c)) {
parser.q = c
parser.state = S.ATTRIB_VALUE_QUOTED
} else {
strictFail(parser, 'Unquoted attribute value')
parser.state = S.ATTRIB_VALUE_UNQUOTED
parser.attribValue = c
}
continue
case S.ATTRIB_VALUE_QUOTED:
if (c !== parser.q) {
if (c === '&') {
parser.state = S.ATTRIB_VALUE_ENTITY_Q
} else {
parser.attribValue += c
}
continue
}
attrib(parser)
parser.q = ''
parser.state = S.ATTRIB_VALUE_CLOSED
continue
case S.ATTRIB_VALUE_CLOSED:
if (is(whitespace, c)) {
parser.state = S.ATTRIB
} else if (c === '>') {
openTag(parser)
} else if (c === '/') {
parser.state = S.OPEN_TAG_SLASH
} else if (is(nameStart, c)) {
strictFail(parser, 'No whitespace between attributes')
parser.attribName = c
parser.attribValue = ''
parser.state = S.ATTRIB_NAME
} else {
strictFail(parser, 'Invalid attribute name')
}
continue
case S.ATTRIB_VALUE_UNQUOTED:
if (not(attribEnd, c)) {
if (c === '&') {
parser.state = S.ATTRIB_VALUE_ENTITY_U
} else {
parser.attribValue += c
}
continue
}
attrib(parser)
if (c === '>') {
openTag(parser)
} else {
parser.state = S.ATTRIB
}
continue
case S.CLOSE_TAG:
if (!parser.tagName) {
if (is(whitespace, c)) {
continue
} else if (not(nameStart, c)) {
if (parser.script) {
parser.script += '</' + c
parser.state = S.SCRIPT
} else {
strictFail(parser, 'Invalid tagname in closing tag.')
}
} else {
parser.tagName = c
}
} else if (c === '>') {
closeTag(parser)
} else if (is(nameBody, c)) {
parser.tagName += c
} else if (parser.script) {
parser.script += '</' + parser.tagName
parser.tagName = ''
parser.state = S.SCRIPT
} else {
if (not(whitespace, c)) {
strictFail(parser, 'Invalid tagname in closing tag')
}
parser.state = S.CLOSE_TAG_SAW_WHITE
}
continue
case S.CLOSE_TAG_SAW_WHITE:
if (is(whitespace, c)) {
continue
}
if (c === '>') {
closeTag(parser)
} else {
strictFail(parser, 'Invalid characters in closing tag')
}
continue
case S.TEXT_ENTITY:
case S.ATTRIB_VALUE_ENTITY_Q:
case S.ATTRIB_VALUE_ENTITY_U:
var returnState
var buffer
switch (parser.state) {
case S.TEXT_ENTITY:
returnState = S.TEXT
buffer = 'textNode'
break
case S.ATTRIB_VALUE_ENTITY_Q:
returnState = S.ATTRIB_VALUE_QUOTED
buffer = 'attribValue'
break
case S.ATTRIB_VALUE_ENTITY_U:
returnState = S.ATTRIB_VALUE_UNQUOTED
buffer = 'attribValue'
break
}
if (c === ';') {
parser[buffer] += parseEntity(parser)
parser.entity = ''
parser.state = returnState
} else if (is(parser.entity.length ? entityBody : entityStart, c)) {
parser.entity += c
} else {
strictFail(parser, 'Invalid character in entity name')
parser[buffer] += '&' + parser.entity + c
parser.entity = ''
parser.state = returnState
}
continue
default:
throw new Error(parser, 'Unknown state: ' + parser.state)
}
} // while
if (parser.position >= parser.bufferCheckPosition) {
checkBufferLength(parser)
}
return parser
}
/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */
Iif (!String.fromCodePoint) {
(function () {
var stringFromCharCode = String.fromCharCode
var floor = Math.floor
var fromCodePoint = function () {
var MAX_SIZE = 0x4000
var codeUnits = []
var highSurrogate
var lowSurrogate
var index = -1
var length = arguments.length
if (!length) {
return ''
}
var result = ''
while (++index < length) {
var codePoint = Number(arguments[index])
if (
!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
codePoint < 0 || // not a valid Unicode code point
codePoint > 0x10FFFF || // not a valid Unicode code point
floor(codePoint) !== codePoint // not an integer
) {
throw RangeError('Invalid code point: ' + codePoint)
}
if (codePoint <= 0xFFFF) { // BMP code point
codeUnits.push(codePoint)
} else { // Astral code point; split in surrogate halves
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000
highSurrogate = (codePoint >> 10) + 0xD800
lowSurrogate = (codePoint % 0x400) + 0xDC00
codeUnits.push(highSurrogate, lowSurrogate)
}
if (index + 1 === length || codeUnits.length > MAX_SIZE) {
result += stringFromCharCode.apply(null, codeUnits)
codeUnits.length = 0
}
}
return result
}
if (Object.defineProperty) {
Object.defineProperty(String, 'fromCodePoint', {
value: fromCodePoint,
configurable: true,
writable: true
})
} else {
String.fromCodePoint = fromCodePoint
}
}())
}
})(typeof exports === 'undefined' ? this.sax = {} : exports)
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| bom.js | 57.14% | (4 / 7) | 0% | (0 / 2) | 50% | (1 / 2) | 57.14% | (4 / 7) | |
| processors.js | 47.06% | (8 / 17) | 0% | (0 / 6) | 16.67% | (1 / 6) | 47.06% | (8 / 17) | |
| xml2js.js | 12.62% | (41 / 325) | 0.53% | (1 / 190) | 15.38% | (6 / 39) | 10.71% | (33 / 308) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 1 1 1 1 | // Generated by CoffeeScript 1.10.0
(function() {
"use strict";
var xml2js;
xml2js = require('../lib/xml2js');
exports.stripBOM = function(str) {
if (str[0] === '\uFEFF') {
return str.substring(1);
} else {
return str;
}
};
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.10.0
(function() {
"use strict";
var prefixMatch;
prefixMatch = new RegExp(/(?!xmlns)^.*:/);
exports.normalize = function(str) {
return str.toLowerCase();
};
exports.firstCharLowerCase = function(str) {
return str.charAt(0).toLowerCase() + str.slice(1);
};
exports.stripPrefix = function(str) {
return str.replace(prefixMatch, '');
};
exports.parseNumbers = function(str) {
if (!isNaN(str)) {
str = str % 1 === 0 ? parseInt(str, 10) : parseFloat(str);
}
return str;
};
exports.parseBooleans = function(str) {
if (/^(?:true|false)$/i.test(str)) {
str = str.toLowerCase() === 'true';
}
return str;
};
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 | 1 1 7 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.10.0
(function() {
"use strict";
var bom, builder, escapeCDATA, events, isEmpty, processName, processors, requiresCDATA, sax, setImmediate, wrapCDATA,
extend = function(child, parent) { for (var key in parent) { Eif (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
sax = require('sax');
events = require('events');
builder = require('xmlbuilder');
bom = require('./bom');
processors = require('./processors');
setImmediate = require('timers').setImmediate;
isEmpty = function(thing) {
return typeof thing === "object" && (thing != null) && Object.keys(thing).length === 0;
};
processName = function(processors, processedName) {
var i, len, process;
for (i = 0, len = processors.length; i < len; i++) {
process = processors[i];
processedName = process(processedName);
}
return processedName;
};
requiresCDATA = function(entry) {
return entry.indexOf('&') >= 0 || entry.indexOf('>') >= 0 || entry.indexOf('<') >= 0;
};
wrapCDATA = function(entry) {
return "<![CDATA[" + (escapeCDATA(entry)) + "]]>";
};
escapeCDATA = function(entry) {
return entry.replace(']]>', ']]]]><![CDATA[>');
};
exports.processors = processors;
exports.defaults = {
"0.1": {
explicitCharkey: false,
trim: true,
normalize: true,
normalizeTags: false,
attrkey: "@",
charkey: "#",
explicitArray: false,
ignoreAttrs: false,
mergeAttrs: false,
explicitRoot: false,
validator: null,
xmlns: false,
explicitChildren: false,
childkey: '@@',
charsAsChildren: false,
async: false,
strict: true,
attrNameProcessors: null,
attrValueProcessors: null,
tagNameProcessors: null,
valueProcessors: null,
emptyTag: ''
},
"0.2": {
explicitCharkey: false,
trim: false,
normalize: false,
normalizeTags: false,
attrkey: "$",
charkey: "_",
explicitArray: true,
ignoreAttrs: false,
mergeAttrs: false,
explicitRoot: true,
validator: null,
xmlns: false,
explicitChildren: false,
preserveChildrenOrder: false,
childkey: '$$',
charsAsChildren: false,
async: false,
strict: true,
attrNameProcessors: null,
attrValueProcessors: null,
tagNameProcessors: null,
valueProcessors: null,
rootName: 'root',
xmldec: {
'version': '1.0',
'encoding': 'UTF-8',
'standalone': true
},
doctype: null,
renderOpts: {
'pretty': true,
'indent': ' ',
'newline': '\n'
},
headless: false,
chunkSize: 10000,
emptyTag: '',
cdata: false
}
};
exports.ValidationError = (function(superClass) {
extend(ValidationError, superClass);
function ValidationError(message) {
this.message = message;
}
return ValidationError;
})(Error);
exports.Builder = (function() {
function Builder(opts) {
var key, ref, value;
this.options = {};
ref = exports.defaults["0.2"];
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
value = ref[key];
this.options[key] = value;
}
for (key in opts) {
if (!hasProp.call(opts, key)) continue;
value = opts[key];
this.options[key] = value;
}
}
Builder.prototype.buildObject = function(rootObj) {
var attrkey, charkey, render, rootElement, rootName;
attrkey = this.options.attrkey;
charkey = this.options.charkey;
if ((Object.keys(rootObj).length === 1) && (this.options.rootName === exports.defaults['0.2'].rootName)) {
rootName = Object.keys(rootObj)[0];
rootObj = rootObj[rootName];
} else {
rootName = this.options.rootName;
}
render = (function(_this) {
return function(element, obj) {
var attr, child, entry, index, key, value;
if (typeof obj !== 'object') {
if (_this.options.cdata && requiresCDATA(obj)) {
element.raw(wrapCDATA(obj));
} else {
element.txt(obj);
}
} else {
for (key in obj) {
if (!hasProp.call(obj, key)) continue;
child = obj[key];
if (key === attrkey) {
if (typeof child === "object") {
for (attr in child) {
value = child[attr];
element = element.att(attr, value);
}
}
} else if (key === charkey) {
if (_this.options.cdata && requiresCDATA(child)) {
element = element.raw(wrapCDATA(child));
} else {
element = element.txt(child);
}
} else if (Array.isArray(child)) {
for (index in child) {
if (!hasProp.call(child, index)) continue;
entry = child[index];
if (typeof entry === 'string') {
if (_this.options.cdata && requiresCDATA(entry)) {
element = element.ele(key).raw(wrapCDATA(entry)).up();
} else {
element = element.ele(key, entry).up();
}
} else {
element = render(element.ele(key), entry).up();
}
}
} else if (typeof child === "object") {
element = render(element.ele(key), child).up();
} else {
if (typeof child === 'string' && _this.options.cdata && requiresCDATA(child)) {
element = element.ele(key).raw(wrapCDATA(child)).up();
} else {
if (child == null) {
child = '';
}
element = element.ele(key, child.toString()).up();
}
}
}
}
return element;
};
})(this);
rootElement = builder.create(rootName, this.options.xmldec, this.options.doctype, {
headless: this.options.headless
});
return render(rootElement, rootObj).end(this.options.renderOpts);
};
return Builder;
})();
exports.Parser = (function(superClass) {
extend(Parser, superClass);
function Parser(opts) {
this.parseString = bind(this.parseString, this);
this.reset = bind(this.reset, this);
this.assignOrPush = bind(this.assignOrPush, this);
this.processAsync = bind(this.processAsync, this);
var key, ref, value;
if (!(this instanceof exports.Parser)) {
return new exports.Parser(opts);
}
this.options = {};
ref = exports.defaults["0.2"];
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
value = ref[key];
this.options[key] = value;
}
for (key in opts) {
if (!hasProp.call(opts, key)) continue;
value = opts[key];
this.options[key] = value;
}
if (this.options.xmlns) {
this.options.xmlnskey = this.options.attrkey + "ns";
}
if (this.options.normalizeTags) {
if (!this.options.tagNameProcessors) {
this.options.tagNameProcessors = [];
}
this.options.tagNameProcessors.unshift(processors.normalize);
}
this.reset();
}
Parser.prototype.processAsync = function() {
var chunk, err, error1;
try {
if (this.remaining.length <= this.options.chunkSize) {
chunk = this.remaining;
this.remaining = '';
this.saxParser = this.saxParser.write(chunk);
return this.saxParser.close();
} else {
chunk = this.remaining.substr(0, this.options.chunkSize);
this.remaining = this.remaining.substr(this.options.chunkSize, this.remaining.length);
this.saxParser = this.saxParser.write(chunk);
return setImmediate(this.processAsync);
}
} catch (error1) {
err = error1;
if (!this.saxParser.errThrown) {
this.saxParser.errThrown = true;
return this.emit(err);
}
}
};
Parser.prototype.assignOrPush = function(obj, key, newValue) {
if (!(key in obj)) {
if (!this.options.explicitArray) {
return obj[key] = newValue;
} else {
return obj[key] = [newValue];
}
} else {
if (!(obj[key] instanceof Array)) {
obj[key] = [obj[key]];
}
return obj[key].push(newValue);
}
};
Parser.prototype.reset = function() {
var attrkey, charkey, ontext, stack;
this.removeAllListeners();
this.saxParser = sax.parser(this.options.strict, {
trim: false,
normalize: false,
xmlns: this.options.xmlns
});
this.saxParser.errThrown = false;
this.saxParser.onerror = (function(_this) {
return function(error) {
_this.saxParser.resume();
if (!_this.saxParser.errThrown) {
_this.saxParser.errThrown = true;
return _this.emit("error", error);
}
};
})(this);
this.saxParser.onend = (function(_this) {
return function() {
if (!_this.saxParser.ended) {
_this.saxParser.ended = true;
return _this.emit("end", _this.resultObject);
}
};
})(this);
this.saxParser.ended = false;
this.EXPLICIT_CHARKEY = this.options.explicitCharkey;
this.resultObject = null;
stack = [];
attrkey = this.options.attrkey;
charkey = this.options.charkey;
this.saxParser.onopentag = (function(_this) {
return function(node) {
var key, newValue, obj, processedKey, ref;
obj = {};
obj[charkey] = "";
if (!_this.options.ignoreAttrs) {
ref = node.attributes;
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
if (!(attrkey in obj) && !_this.options.mergeAttrs) {
obj[attrkey] = {};
}
newValue = _this.options.attrValueProcessors ? processName(_this.options.attrValueProcessors, node.attributes[key]) : node.attributes[key];
processedKey = _this.options.attrNameProcessors ? processName(_this.options.attrNameProcessors, key) : key;
if (_this.options.mergeAttrs) {
_this.assignOrPush(obj, processedKey, newValue);
} else {
obj[attrkey][processedKey] = newValue;
}
}
}
obj["#name"] = _this.options.tagNameProcessors ? processName(_this.options.tagNameProcessors, node.name) : node.name;
if (_this.options.xmlns) {
obj[_this.options.xmlnskey] = {
uri: node.uri,
local: node.local
};
}
return stack.push(obj);
};
})(this);
this.saxParser.onclosetag = (function(_this) {
return function() {
var cdata, emptyStr, err, error1, key, node, nodeName, obj, objClone, old, s, xpath;
obj = stack.pop();
nodeName = obj["#name"];
if (!_this.options.explicitChildren || !_this.options.preserveChildrenOrder) {
delete obj["#name"];
}
if (obj.cdata === true) {
cdata = obj.cdata;
delete obj.cdata;
}
s = stack[stack.length - 1];
if (obj[charkey].match(/^\s*$/) && !cdata) {
emptyStr = obj[charkey];
delete obj[charkey];
} else {
if (_this.options.trim) {
obj[charkey] = obj[charkey].trim();
}
if (_this.options.normalize) {
obj[charkey] = obj[charkey].replace(/\s{2,}/g, " ").trim();
}
obj[charkey] = _this.options.valueProcessors ? processName(_this.options.valueProcessors, obj[charkey]) : obj[charkey];
if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) {
obj = obj[charkey];
}
}
if (isEmpty(obj)) {
obj = _this.options.emptyTag !== '' ? _this.options.emptyTag : emptyStr;
}
if (_this.options.validator != null) {
xpath = "/" + ((function() {
var i, len, results;
results = [];
for (i = 0, len = stack.length; i < len; i++) {
node = stack[i];
results.push(node["#name"]);
}
return results;
})()).concat(nodeName).join("/");
try {
obj = _this.options.validator(xpath, s && s[nodeName], obj);
} catch (error1) {
err = error1;
_this.emit("error", err);
}
}
if (_this.options.explicitChildren && !_this.options.mergeAttrs && typeof obj === 'object') {
if (!_this.options.preserveChildrenOrder) {
node = {};
if (_this.options.attrkey in obj) {
node[_this.options.attrkey] = obj[_this.options.attrkey];
delete obj[_this.options.attrkey];
}
if (!_this.options.charsAsChildren && _this.options.charkey in obj) {
node[_this.options.charkey] = obj[_this.options.charkey];
delete obj[_this.options.charkey];
}
if (Object.getOwnPropertyNames(obj).length > 0) {
node[_this.options.childkey] = obj;
}
obj = node;
} else if (s) {
s[_this.options.childkey] = s[_this.options.childkey] || [];
objClone = {};
for (key in obj) {
if (!hasProp.call(obj, key)) continue;
objClone[key] = obj[key];
}
s[_this.options.childkey].push(objClone);
delete obj["#name"];
if (Object.keys(obj).length === 1 && charkey in obj && !_this.EXPLICIT_CHARKEY) {
obj = obj[charkey];
}
}
}
if (stack.length > 0) {
return _this.assignOrPush(s, nodeName, obj);
} else {
if (_this.options.explicitRoot) {
old = obj;
obj = {};
obj[nodeName] = old;
}
_this.resultObject = obj;
_this.saxParser.ended = true;
return _this.emit("end", _this.resultObject);
}
};
})(this);
ontext = (function(_this) {
return function(text) {
var charChild, s;
s = stack[stack.length - 1];
if (s) {
s[charkey] += text;
if (_this.options.explicitChildren && _this.options.preserveChildrenOrder && _this.options.charsAsChildren && text.replace(/\\n/g, '').trim() !== '') {
s[_this.options.childkey] = s[_this.options.childkey] || [];
charChild = {
'#name': '__text__'
};
charChild[charkey] = text;
s[_this.options.childkey].push(charChild);
}
return s;
}
};
})(this);
this.saxParser.ontext = ontext;
return this.saxParser.oncdata = (function(_this) {
return function(text) {
var s;
s = ontext(text);
if (s) {
return s.cdata = true;
}
};
})(this);
};
Parser.prototype.parseString = function(str, cb) {
var err, error1;
if ((cb != null) && typeof cb === "function") {
this.on("end", function(result) {
this.reset();
return cb(null, result);
});
this.on("error", function(err) {
this.reset();
return cb(err);
});
}
try {
str = str.toString();
if (str.trim() === '') {
this.emit("end", null);
return true;
}
str = bom.stripBOM(str);
if (this.options.async) {
this.remaining = str;
setImmediate(this.processAsync);
return this.saxParser;
}
return this.saxParser.write(str).close();
} catch (error1) {
err = error1;
if (!(this.saxParser.errThrown || this.saxParser.ended)) {
this.emit('error', err);
return this.saxParser.errThrown = true;
} else if (this.saxParser.ended) {
throw err;
}
}
};
return Parser;
})(events.EventEmitter);
exports.parseString = function(str, a, b) {
var cb, options, parser;
if (b != null) {
if (typeof b === 'function') {
cb = b;
}
if (typeof a === 'object') {
options = a;
}
} else {
if (typeof a === 'function') {
cb = a;
}
options = {};
}
parser = new exports.Parser(options);
return parser.parseString(str, cb);
};
}).call(this);
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| XMLAttribute.js | 47.06% | (8 / 17) | 0% | (0 / 4) | 40% | (2 / 5) | 47.06% | (8 / 17) | |
| XMLBuilder.js | 27.27% | (12 / 44) | 0% | (0 / 34) | 33.33% | (2 / 6) | 27.27% | (12 / 44) | |
| XMLCData.js | 44.74% | (17 / 38) | 0% | (0 / 26) | 57.14% | (4 / 7) | 36.67% | (11 / 30) | |
| XMLComment.js | 44.74% | (17 / 38) | 0% | (0 / 26) | 57.14% | (4 / 7) | 36.67% | (11 / 30) | |
| XMLDTDAttList.js | 16.67% | (8 / 48) | 0% | (0 / 42) | 40% | (2 / 5) | 16.67% | (8 / 48) | |
| XMLDTDElement.js | 27.27% | (9 / 33) | 0% | (0 / 28) | 40% | (2 / 5) | 27.27% | (9 / 33) | |
| XMLDTDEntity.js | 15.79% | (9 / 57) | 0% | (0 / 58) | 40% | (2 / 5) | 15.79% | (9 / 57) | |
| XMLDTDNotation.js | 20% | (8 / 40) | 0% | (0 / 40) | 40% | (2 / 5) | 20% | (8 / 40) | |
| XMLDeclaration.js | 33.33% | (18 / 54) | 0% | (0 / 40) | 57.14% | (4 / 7) | 26.09% | (12 / 46) | |
| XMLDocType.js | 29.75% | (36 / 121) | 0% | (0 / 40) | 8% | (2 / 25) | 29.75% | (36 / 121) | |
| XMLElement.js | 19.23% | (30 / 156) | 0% | (0 / 77) | 25% | (4 / 16) | 16.67% | (24 / 144) | |
| XMLNode.js | 23.15% | (50 / 216) | 0% | (0 / 90) | 5.41% | (2 / 37) | 23.26% | (50 / 215) | |
| XMLProcessingInstruction.js | 24.24% | (8 / 33) | 0% | (0 / 28) | 40% | (2 / 5) | 24.24% | (8 / 33) | |
| XMLStringifier.js | 35.42% | (34 / 96) | 0% | (0 / 62) | 7.41% | (2 / 27) | 36.17% | (34 / 94) | |
| index.js | 71.43% | (5 / 7) | 100% | (0 / 0) | 50% | (1 / 2) | 71.43% | (5 / 7) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLAttribute, create;
create = require('lodash/object/create');
module.exports = XMLAttribute = (function() {
function XMLAttribute(parent, name, value) {
this.stringify = parent.stringify;
if (name == null) {
throw new Error("Missing attribute name of element " + parent.name);
}
if (value == null) {
throw new Error("Missing attribute value for attribute " + name + " of element " + parent.name);
}
this.name = this.stringify.attName(name);
this.value = this.stringify.attValue(value);
}
XMLAttribute.prototype.clone = function() {
return create(XMLAttribute.prototype, this);
};
XMLAttribute.prototype.toString = function(options, level) {
return ' ' + this.name + '="' + this.value + '"';
};
return XMLAttribute;
})();
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 1 1 1 1 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLBuilder, XMLDeclaration, XMLDocType, XMLElement, XMLStringifier;
XMLStringifier = require('./XMLStringifier');
XMLDeclaration = require('./XMLDeclaration');
XMLDocType = require('./XMLDocType');
XMLElement = require('./XMLElement');
module.exports = XMLBuilder = (function() {
function XMLBuilder(name, options) {
var root, temp;
if (name == null) {
throw new Error("Root element needs a name");
}
if (options == null) {
options = {};
}
this.options = options;
this.stringify = new XMLStringifier(options);
temp = new XMLElement(this, 'doc');
root = temp.element(name);
root.isRoot = true;
root.documentObject = this;
this.rootObject = root;
if (!options.headless) {
root.declaration(options);
if ((options.pubID != null) || (options.sysID != null)) {
root.doctype(options);
}
}
}
XMLBuilder.prototype.root = function() {
return this.rootObject;
};
XMLBuilder.prototype.end = function(options) {
return this.toString(options);
};
XMLBuilder.prototype.toString = function(options) {
var indent, newline, offset, pretty, r, ref, ref1, ref2;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
r = '';
if (this.xmldec != null) {
r += this.xmldec.toString(options);
}
if (this.doctype != null) {
r += this.doctype.toString(options);
}
r += this.rootObject.toString(options);
if (pretty && r.slice(-newline.length) === newline) {
r = r.slice(0, -newline.length);
}
return r;
};
return XMLBuilder;
})();
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 1 1 1 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLCData, XMLNode, create,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
create = require('lodash/object/create');
XMLNode = require('./XMLNode');
module.exports = XMLCData = (function(superClass) {
extend(XMLCData, superClass);
function XMLCData(parent, text) {
XMLCData.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing CDATA text");
}
this.text = this.stringify.cdata(text);
}
XMLCData.prototype.clone = function() {
return create(XMLCData.prototype, this);
};
XMLCData.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<![CDATA[' + this.text + ']]>';
if (pretty) {
r += newline;
}
return r;
};
return XMLCData;
})(XMLNode);
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 1 1 1 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLComment, XMLNode, create,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
create = require('lodash/object/create');
XMLNode = require('./XMLNode');
module.exports = XMLComment = (function(superClass) {
extend(XMLComment, superClass);
function XMLComment(parent, text) {
XMLComment.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing comment text");
}
this.text = this.stringify.comment(text);
}
XMLComment.prototype.clone = function() {
return create(XMLComment.prototype, this);
};
XMLComment.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!-- ' + this.text + ' -->';
if (pretty) {
r += newline;
}
return r;
};
return XMLComment;
})(XMLNode);
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLDTDAttList, create;
create = require('lodash/object/create');
module.exports = XMLDTDAttList = (function() {
function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) {
this.stringify = parent.stringify;
if (elementName == null) {
throw new Error("Missing DTD element name");
}
if (attributeName == null) {
throw new Error("Missing DTD attribute name");
}
if (!attributeType) {
throw new Error("Missing DTD attribute type");
}
if (!defaultValueType) {
throw new Error("Missing DTD attribute default");
}
if (defaultValueType.indexOf('#') !== 0) {
defaultValueType = '#' + defaultValueType;
}
if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) {
throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT");
}
if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) {
throw new Error("Default value only applies to #FIXED or #DEFAULT");
}
this.elementName = this.stringify.eleName(elementName);
this.attributeName = this.stringify.attName(attributeName);
this.attributeType = this.stringify.dtdAttType(attributeType);
this.defaultValue = this.stringify.dtdAttDefault(defaultValue);
this.defaultValueType = defaultValueType;
}
XMLDTDAttList.prototype.clone = function() {
return create(XMLDTDAttList.prototype, this);
};
XMLDTDAttList.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!ATTLIST ' + this.elementName + ' ' + this.attributeName + ' ' + this.attributeType;
if (this.defaultValueType !== '#DEFAULT') {
r += ' ' + this.defaultValueType;
}
if (this.defaultValue) {
r += ' "' + this.defaultValue + '"';
}
r += '>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDTDAttList;
})();
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 1 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLDTDElement, create, isArray;
create = require('lodash/object/create');
isArray = require('lodash/lang/isArray');
module.exports = XMLDTDElement = (function() {
function XMLDTDElement(parent, name, value) {
this.stringify = parent.stringify;
if (name == null) {
throw new Error("Missing DTD element name");
}
if (!value) {
value = '(#PCDATA)';
}
if (isArray(value)) {
value = '(' + value.join(',') + ')';
}
this.name = this.stringify.eleName(name);
this.value = this.stringify.dtdElementValue(value);
}
XMLDTDElement.prototype.clone = function() {
return create(XMLDTDElement.prototype, this);
};
XMLDTDElement.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!ELEMENT ' + this.name + ' ' + this.value + '>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDTDElement;
})();
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | 1 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLDTDEntity, create, isObject;
create = require('lodash/object/create');
isObject = require('lodash/lang/isObject');
module.exports = XMLDTDEntity = (function() {
function XMLDTDEntity(parent, pe, name, value) {
this.stringify = parent.stringify;
if (name == null) {
throw new Error("Missing entity name");
}
if (value == null) {
throw new Error("Missing entity value");
}
this.pe = !!pe;
this.name = this.stringify.eleName(name);
if (!isObject(value)) {
this.value = this.stringify.dtdEntityValue(value);
} else {
if (!value.pubID && !value.sysID) {
throw new Error("Public and/or system identifiers are required for an external entity");
}
if (value.pubID && !value.sysID) {
throw new Error("System identifier is required for a public external entity");
}
if (value.pubID != null) {
this.pubID = this.stringify.dtdPubID(value.pubID);
}
if (value.sysID != null) {
this.sysID = this.stringify.dtdSysID(value.sysID);
}
if (value.nData != null) {
this.nData = this.stringify.dtdNData(value.nData);
}
if (this.pe && this.nData) {
throw new Error("Notation declaration is not allowed in a parameter entity");
}
}
}
XMLDTDEntity.prototype.clone = function() {
return create(XMLDTDEntity.prototype, this);
};
XMLDTDEntity.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!ENTITY';
if (this.pe) {
r += ' %';
}
r += ' ' + this.name;
if (this.value) {
r += ' "' + this.value + '"';
} else {
if (this.pubID && this.sysID) {
r += ' PUBLIC "' + this.pubID + '" "' + this.sysID + '"';
} else if (this.sysID) {
r += ' SYSTEM "' + this.sysID + '"';
}
if (this.nData) {
r += ' NDATA ' + this.nData;
}
}
r += '>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDTDEntity;
})();
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLDTDNotation, create;
create = require('lodash/object/create');
module.exports = XMLDTDNotation = (function() {
function XMLDTDNotation(parent, name, value) {
this.stringify = parent.stringify;
if (name == null) {
throw new Error("Missing notation name");
}
if (!value.pubID && !value.sysID) {
throw new Error("Public or system identifiers are required for an external entity");
}
this.name = this.stringify.eleName(name);
if (value.pubID != null) {
this.pubID = this.stringify.dtdPubID(value.pubID);
}
if (value.sysID != null) {
this.sysID = this.stringify.dtdSysID(value.sysID);
}
}
XMLDTDNotation.prototype.clone = function() {
return create(XMLDTDNotation.prototype, this);
};
XMLDTDNotation.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!NOTATION ' + this.name;
if (this.pubID && this.sysID) {
r += ' PUBLIC "' + this.pubID + '" "' + this.sysID + '"';
} else if (this.pubID) {
r += ' PUBLIC "' + this.pubID + '"';
} else if (this.sysID) {
r += ' SYSTEM "' + this.sysID + '"';
}
r += '>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDTDNotation;
})();
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | 1 1 1 1 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLDeclaration, XMLNode, create, isObject,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
create = require('lodash/object/create');
isObject = require('lodash/lang/isObject');
XMLNode = require('./XMLNode');
module.exports = XMLDeclaration = (function(superClass) {
extend(XMLDeclaration, superClass);
function XMLDeclaration(parent, version, encoding, standalone) {
var ref;
XMLDeclaration.__super__.constructor.call(this, parent);
if (isObject(version)) {
ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone;
}
if (!version) {
version = '1.0';
}
if (version != null) {
this.version = this.stringify.xmlVersion(version);
}
if (encoding != null) {
this.encoding = this.stringify.xmlEncoding(encoding);
}
if (standalone != null) {
this.standalone = this.stringify.xmlStandalone(standalone);
}
}
XMLDeclaration.prototype.clone = function() {
return create(XMLDeclaration.prototype, this);
};
XMLDeclaration.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<?xml';
if (this.version != null) {
r += ' version="' + this.version + '"';
}
if (this.encoding != null) {
r += ' encoding="' + this.encoding + '"';
}
if (this.standalone != null) {
r += ' standalone="' + this.standalone + '"';
}
r += '?>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDeclaration;
})(XMLNode);
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLProcessingInstruction, create, isObject;
create = require('lodash/object/create');
isObject = require('lodash/lang/isObject');
XMLCData = require('./XMLCData');
XMLComment = require('./XMLComment');
XMLDTDAttList = require('./XMLDTDAttList');
XMLDTDEntity = require('./XMLDTDEntity');
XMLDTDElement = require('./XMLDTDElement');
XMLDTDNotation = require('./XMLDTDNotation');
XMLProcessingInstruction = require('./XMLProcessingInstruction');
module.exports = XMLDocType = (function() {
function XMLDocType(parent, pubID, sysID) {
var ref, ref1;
this.documentObject = parent;
this.stringify = this.documentObject.stringify;
this.children = [];
if (isObject(pubID)) {
ref = pubID, pubID = ref.pubID, sysID = ref.sysID;
}
if (sysID == null) {
ref1 = [pubID, sysID], sysID = ref1[0], pubID = ref1[1];
}
if (pubID != null) {
this.pubID = this.stringify.dtdPubID(pubID);
}
if (sysID != null) {
this.sysID = this.stringify.dtdSysID(sysID);
}
}
XMLDocType.prototype.clone = function() {
return create(XMLDocType.prototype, this);
};
XMLDocType.prototype.element = function(name, value) {
var child;
child = new XMLDTDElement(this, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
var child;
child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
this.children.push(child);
return this;
};
XMLDocType.prototype.entity = function(name, value) {
var child;
child = new XMLDTDEntity(this, false, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.pEntity = function(name, value) {
var child;
child = new XMLDTDEntity(this, true, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.notation = function(name, value) {
var child;
child = new XMLDTDNotation(this, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.cdata = function(value) {
var child;
child = new XMLCData(this, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.comment = function(value) {
var child;
child = new XMLComment(this, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.instruction = function(target, value) {
var child;
child = new XMLProcessingInstruction(this, target, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.root = function() {
return this.documentObject.root();
};
XMLDocType.prototype.document = function() {
return this.documentObject;
};
XMLDocType.prototype.toString = function(options, level) {
var child, i, indent, len, newline, offset, pretty, r, ref, ref1, ref2, ref3, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!DOCTYPE ' + this.root().name;
if (this.pubID && this.sysID) {
r += ' PUBLIC "' + this.pubID + '" "' + this.sysID + '"';
} else if (this.sysID) {
r += ' SYSTEM "' + this.sysID + '"';
}
if (this.children.length > 0) {
r += ' [';
if (pretty) {
r += newline;
}
ref3 = this.children;
for (i = 0, len = ref3.length; i < len; i++) {
child = ref3[i];
r += child.toString(options, level + 1);
}
r += ']';
}
r += '>';
if (pretty) {
r += newline;
}
return r;
};
XMLDocType.prototype.ele = function(name, value) {
return this.element(name, value);
};
XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue);
};
XMLDocType.prototype.ent = function(name, value) {
return this.entity(name, value);
};
XMLDocType.prototype.pent = function(name, value) {
return this.pEntity(name, value);
};
XMLDocType.prototype.not = function(name, value) {
return this.notation(name, value);
};
XMLDocType.prototype.dat = function(value) {
return this.cdata(value);
};
XMLDocType.prototype.com = function(value) {
return this.comment(value);
};
XMLDocType.prototype.ins = function(target, value) {
return this.instruction(target, value);
};
XMLDocType.prototype.up = function() {
return this.root();
};
XMLDocType.prototype.doc = function() {
return this.document();
};
return XMLDocType;
})();
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLAttribute, XMLElement, XMLNode, XMLProcessingInstruction, create, every, isArray, isFunction, isObject,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
create = require('lodash/object/create');
isObject = require('lodash/lang/isObject');
isArray = require('lodash/lang/isArray');
isFunction = require('lodash/lang/isFunction');
every = require('lodash/collection/every');
XMLNode = require('./XMLNode');
XMLAttribute = require('./XMLAttribute');
XMLProcessingInstruction = require('./XMLProcessingInstruction');
module.exports = XMLElement = (function(superClass) {
extend(XMLElement, superClass);
function XMLElement(parent, name, attributes) {
XMLElement.__super__.constructor.call(this, parent);
if (name == null) {
throw new Error("Missing element name");
}
this.name = this.stringify.eleName(name);
this.children = [];
this.instructions = [];
this.attributes = {};
if (attributes != null) {
this.attribute(attributes);
}
}
XMLElement.prototype.clone = function() {
var att, attName, clonedSelf, i, len, pi, ref, ref1;
clonedSelf = create(XMLElement.prototype, this);
if (clonedSelf.isRoot) {
clonedSelf.documentObject = null;
}
clonedSelf.attributes = {};
ref = this.attributes;
for (attName in ref) {
if (!hasProp.call(ref, attName)) continue;
att = ref[attName];
clonedSelf.attributes[attName] = att.clone();
}
clonedSelf.instructions = [];
ref1 = this.instructions;
for (i = 0, len = ref1.length; i < len; i++) {
pi = ref1[i];
clonedSelf.instructions.push(pi.clone());
}
clonedSelf.children = [];
this.children.forEach(function(child) {
var clonedChild;
clonedChild = child.clone();
clonedChild.parent = clonedSelf;
return clonedSelf.children.push(clonedChild);
});
return clonedSelf;
};
XMLElement.prototype.attribute = function(name, value) {
var attName, attValue;
if (name != null) {
name = name.valueOf();
}
if (isObject(name)) {
for (attName in name) {
if (!hasProp.call(name, attName)) continue;
attValue = name[attName];
this.attribute(attName, attValue);
}
} else {
if (isFunction(value)) {
value = value.apply();
}
if (!this.options.skipNullAttributes || (value != null)) {
this.attributes[name] = new XMLAttribute(this, name, value);
}
}
return this;
};
XMLElement.prototype.removeAttribute = function(name) {
var attName, i, len;
if (name == null) {
throw new Error("Missing attribute name");
}
name = name.valueOf();
if (isArray(name)) {
for (i = 0, len = name.length; i < len; i++) {
attName = name[i];
delete this.attributes[attName];
}
} else {
delete this.attributes[name];
}
return this;
};
XMLElement.prototype.instruction = function(target, value) {
var i, insTarget, insValue, instruction, len;
if (target != null) {
target = target.valueOf();
}
if (value != null) {
value = value.valueOf();
}
if (isArray(target)) {
for (i = 0, len = target.length; i < len; i++) {
insTarget = target[i];
this.instruction(insTarget);
}
} else if (isObject(target)) {
for (insTarget in target) {
if (!hasProp.call(target, insTarget)) continue;
insValue = target[insTarget];
this.instruction(insTarget, insValue);
}
} else {
if (isFunction(value)) {
value = value.apply();
}
instruction = new XMLProcessingInstruction(this, target, value);
this.instructions.push(instruction);
}
return this;
};
XMLElement.prototype.toString = function(options, level) {
var att, child, i, indent, instruction, j, len, len1, name, newline, offset, pretty, r, ref, ref1, ref2, ref3, ref4, ref5, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
ref3 = this.instructions;
for (i = 0, len = ref3.length; i < len; i++) {
instruction = ref3[i];
r += instruction.toString(options, level + 1);
}
if (pretty) {
r += space;
}
r += '<' + this.name;
ref4 = this.attributes;
for (name in ref4) {
if (!hasProp.call(ref4, name)) continue;
att = ref4[name];
r += att.toString(options);
}
if (this.children.length === 0 || every(this.children, function(e) {
return e.value === '';
})) {
r += '/>';
if (pretty) {
r += newline;
}
} else if (pretty && this.children.length === 1 && (this.children[0].value != null)) {
r += '>';
r += this.children[0].value;
r += '</' + this.name + '>';
r += newline;
} else {
r += '>';
if (pretty) {
r += newline;
}
ref5 = this.children;
for (j = 0, len1 = ref5.length; j < len1; j++) {
child = ref5[j];
r += child.toString(options, level + 1);
}
if (pretty) {
r += space;
}
r += '</' + this.name + '>';
if (pretty) {
r += newline;
}
}
return r;
};
XMLElement.prototype.att = function(name, value) {
return this.attribute(name, value);
};
XMLElement.prototype.ins = function(target, value) {
return this.instruction(target, value);
};
XMLElement.prototype.a = function(name, value) {
return this.attribute(name, value);
};
XMLElement.prototype.i = function(target, value) {
return this.instruction(target, value);
};
return XMLElement;
})(XMLNode);
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLElement, XMLNode, XMLRaw, XMLText, isArray, isEmpty, isFunction, isObject,
hasProp = {}.hasOwnProperty;
isObject = require('lodash/lang/isObject');
isArray = require('lodash/lang/isArray');
isFunction = require('lodash/lang/isFunction');
isEmpty = require('lodash/lang/isEmpty');
XMLElement = null;
XMLCData = null;
XMLComment = null;
XMLDeclaration = null;
XMLDocType = null;
XMLRaw = null;
XMLText = null;
module.exports = XMLNode = (function() {
function XMLNode(parent) {
this.parent = parent;
this.options = this.parent.options;
this.stringify = this.parent.stringify;
if (XMLElement === null) {
XMLElement = require('./XMLElement');
XMLCData = require('./XMLCData');
XMLComment = require('./XMLComment');
XMLDeclaration = require('./XMLDeclaration');
XMLDocType = require('./XMLDocType');
XMLRaw = require('./XMLRaw');
XMLText = require('./XMLText');
}
}
XMLNode.prototype.clone = function() {
throw new Error("Cannot clone generic XMLNode");
};
XMLNode.prototype.element = function(name, attributes, text) {
var item, j, key, lastChild, len, ref, val;
lastChild = null;
if (attributes == null) {
attributes = {};
}
attributes = attributes.valueOf();
if (!isObject(attributes)) {
ref = [attributes, text], text = ref[0], attributes = ref[1];
}
if (name != null) {
name = name.valueOf();
}
if (isArray(name)) {
for (j = 0, len = name.length; j < len; j++) {
item = name[j];
lastChild = this.element(item);
}
} else if (isFunction(name)) {
lastChild = this.element(name.apply());
} else if (isObject(name)) {
for (key in name) {
if (!hasProp.call(name, key)) continue;
val = name[key];
if (isFunction(val)) {
val = val.apply();
}
if ((isObject(val)) && (isEmpty(val))) {
val = null;
}
if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) {
lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val);
} else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && key.indexOf(this.stringify.convertPIKey) === 0) {
lastChild = this.instruction(key.substr(this.stringify.convertPIKey.length), val);
} else if (isObject(val)) {
if (!this.options.ignoreDecorators && this.stringify.convertListKey && key.indexOf(this.stringify.convertListKey) === 0 && isArray(val)) {
lastChild = this.element(val);
} else {
lastChild = this.element(key);
lastChild.element(val);
}
} else {
lastChild = this.element(key, val);
}
}
} else {
if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) {
lastChild = this.text(text);
} else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) {
lastChild = this.cdata(text);
} else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) {
lastChild = this.comment(text);
} else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) {
lastChild = this.raw(text);
} else {
lastChild = this.node(name, attributes, text);
}
}
if (lastChild == null) {
throw new Error("Could not create any elements with: " + name);
}
return lastChild;
};
XMLNode.prototype.insertBefore = function(name, attributes, text) {
var child, i, removed;
if (this.isRoot) {
throw new Error("Cannot insert elements at root level");
}
i = this.parent.children.indexOf(this);
removed = this.parent.children.splice(i);
child = this.parent.element(name, attributes, text);
Array.prototype.push.apply(this.parent.children, removed);
return child;
};
XMLNode.prototype.insertAfter = function(name, attributes, text) {
var child, i, removed;
if (this.isRoot) {
throw new Error("Cannot insert elements at root level");
}
i = this.parent.children.indexOf(this);
removed = this.parent.children.splice(i + 1);
child = this.parent.element(name, attributes, text);
Array.prototype.push.apply(this.parent.children, removed);
return child;
};
XMLNode.prototype.remove = function() {
var i, ref;
if (this.isRoot) {
throw new Error("Cannot remove the root element");
}
i = this.parent.children.indexOf(this);
[].splice.apply(this.parent.children, [i, i - i + 1].concat(ref = [])), ref;
return this.parent;
};
XMLNode.prototype.node = function(name, attributes, text) {
var child, ref;
if (name != null) {
name = name.valueOf();
}
if (attributes == null) {
attributes = {};
}
attributes = attributes.valueOf();
if (!isObject(attributes)) {
ref = [attributes, text], text = ref[0], attributes = ref[1];
}
child = new XMLElement(this, name, attributes);
if (text != null) {
child.text(text);
}
this.children.push(child);
return child;
};
XMLNode.prototype.text = function(value) {
var child;
child = new XMLText(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.cdata = function(value) {
var child;
child = new XMLCData(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.comment = function(value) {
var child;
child = new XMLComment(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.raw = function(value) {
var child;
child = new XMLRaw(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.declaration = function(version, encoding, standalone) {
var doc, xmldec;
doc = this.document();
xmldec = new XMLDeclaration(doc, version, encoding, standalone);
doc.xmldec = xmldec;
return doc.root();
};
XMLNode.prototype.doctype = function(pubID, sysID) {
var doc, doctype;
doc = this.document();
doctype = new XMLDocType(doc, pubID, sysID);
doc.doctype = doctype;
return doctype;
};
XMLNode.prototype.up = function() {
if (this.isRoot) {
throw new Error("The root node has no parent. Use doc() if you need to get the document object.");
}
return this.parent;
};
XMLNode.prototype.root = function() {
var child;
if (this.isRoot) {
return this;
}
child = this.parent;
while (!child.isRoot) {
child = child.parent;
}
return child;
};
XMLNode.prototype.document = function() {
return this.root().documentObject;
};
XMLNode.prototype.end = function(options) {
return this.document().toString(options);
};
XMLNode.prototype.prev = function() {
var i;
if (this.isRoot) {
throw new Error("Root node has no siblings");
}
i = this.parent.children.indexOf(this);
if (i < 1) {
throw new Error("Already at the first node");
}
return this.parent.children[i - 1];
};
XMLNode.prototype.next = function() {
var i;
if (this.isRoot) {
throw new Error("Root node has no siblings");
}
i = this.parent.children.indexOf(this);
if (i === -1 || i === this.parent.children.length - 1) {
throw new Error("Already at the last node");
}
return this.parent.children[i + 1];
};
XMLNode.prototype.importXMLBuilder = function(xmlbuilder) {
var clonedRoot;
clonedRoot = xmlbuilder.root().clone();
clonedRoot.parent = this;
clonedRoot.isRoot = false;
this.children.push(clonedRoot);
return this;
};
XMLNode.prototype.ele = function(name, attributes, text) {
return this.element(name, attributes, text);
};
XMLNode.prototype.nod = function(name, attributes, text) {
return this.node(name, attributes, text);
};
XMLNode.prototype.txt = function(value) {
return this.text(value);
};
XMLNode.prototype.dat = function(value) {
return this.cdata(value);
};
XMLNode.prototype.com = function(value) {
return this.comment(value);
};
XMLNode.prototype.doc = function() {
return this.document();
};
XMLNode.prototype.dec = function(version, encoding, standalone) {
return this.declaration(version, encoding, standalone);
};
XMLNode.prototype.dtd = function(pubID, sysID) {
return this.doctype(pubID, sysID);
};
XMLNode.prototype.e = function(name, attributes, text) {
return this.element(name, attributes, text);
};
XMLNode.prototype.n = function(name, attributes, text) {
return this.node(name, attributes, text);
};
XMLNode.prototype.t = function(value) {
return this.text(value);
};
XMLNode.prototype.d = function(value) {
return this.cdata(value);
};
XMLNode.prototype.c = function(value) {
return this.comment(value);
};
XMLNode.prototype.r = function(value) {
return this.raw(value);
};
XMLNode.prototype.u = function() {
return this.up();
};
return XMLNode;
})();
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLProcessingInstruction, create;
create = require('lodash/object/create');
module.exports = XMLProcessingInstruction = (function() {
function XMLProcessingInstruction(parent, target, value) {
this.stringify = parent.stringify;
if (target == null) {
throw new Error("Missing instruction target");
}
this.target = this.stringify.insTarget(target);
if (value) {
this.value = this.stringify.insValue(value);
}
}
XMLProcessingInstruction.prototype.clone = function() {
return create(XMLProcessingInstruction.prototype, this);
};
XMLProcessingInstruction.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<?';
r += this.target;
if (this.value) {
r += ' ' + this.value;
}
r += '?>';
if (pretty) {
r += newline;
}
return r;
};
return XMLProcessingInstruction;
})();
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLStringifier,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
hasProp = {}.hasOwnProperty;
module.exports = XMLStringifier = (function() {
function XMLStringifier(options) {
this.assertLegalChar = bind(this.assertLegalChar, this);
var key, ref, value;
this.allowSurrogateChars = options != null ? options.allowSurrogateChars : void 0;
ref = (options != null ? options.stringify : void 0) || {};
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
value = ref[key];
this[key] = value;
}
}
XMLStringifier.prototype.eleName = function(val) {
val = '' + val || '';
return this.assertLegalChar(val);
};
XMLStringifier.prototype.eleText = function(val) {
val = '' + val || '';
return this.assertLegalChar(this.elEscape(val));
};
XMLStringifier.prototype.cdata = function(val) {
val = '' + val || '';
if (val.match(/]]>/)) {
throw new Error("Invalid CDATA text: " + val);
}
return this.assertLegalChar(val);
};
XMLStringifier.prototype.comment = function(val) {
val = '' + val || '';
if (val.match(/--/)) {
throw new Error("Comment text cannot contain double-hypen: " + val);
}
return this.assertLegalChar(val);
};
XMLStringifier.prototype.raw = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.attName = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.attValue = function(val) {
val = '' + val || '';
return this.attEscape(val);
};
XMLStringifier.prototype.insTarget = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.insValue = function(val) {
val = '' + val || '';
if (val.match(/\?>/)) {
throw new Error("Invalid processing instruction value: " + val);
}
return val;
};
XMLStringifier.prototype.xmlVersion = function(val) {
val = '' + val || '';
if (!val.match(/1\.[0-9]+/)) {
throw new Error("Invalid version number: " + val);
}
return val;
};
XMLStringifier.prototype.xmlEncoding = function(val) {
val = '' + val || '';
if (!val.match(/[A-Za-z](?:[A-Za-z0-9._-]|-)*/)) {
throw new Error("Invalid encoding: " + val);
}
return val;
};
XMLStringifier.prototype.xmlStandalone = function(val) {
if (val) {
return "yes";
} else {
return "no";
}
};
XMLStringifier.prototype.dtdPubID = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdSysID = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdElementValue = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdAttType = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdAttDefault = function(val) {
if (val != null) {
return '' + val || '';
} else {
return val;
}
};
XMLStringifier.prototype.dtdEntityValue = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdNData = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.convertAttKey = '@';
XMLStringifier.prototype.convertPIKey = '?';
XMLStringifier.prototype.convertTextKey = '#text';
XMLStringifier.prototype.convertCDataKey = '#cdata';
XMLStringifier.prototype.convertCommentKey = '#comment';
XMLStringifier.prototype.convertRawKey = '#raw';
XMLStringifier.prototype.convertListKey = '#list';
XMLStringifier.prototype.assertLegalChar = function(str) {
var chars, chr;
if (this.allowSurrogateChars) {
chars = /[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uFFFE-\uFFFF]/;
} else {
chars = /[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]/;
}
chr = str.match(chars);
if (chr) {
throw new Error("Invalid character (" + chr + ") in string: " + str + " at index " + chr.index);
}
return str;
};
XMLStringifier.prototype.elEscape = function(str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\r/g, '
');
};
XMLStringifier.prototype.attEscape = function(str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"').replace(/\t/g, '	').replace(/\n/g, '
').replace(/\r/g, '
');
};
return XMLStringifier;
})();
}).call(this);
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 1 1 1 1 1 | // Generated by CoffeeScript 1.9.1
(function() {
var XMLBuilder, assign;
assign = require('lodash/object/assign');
XMLBuilder = require('./XMLBuilder');
module.exports.create = function(name, xmldec, doctype, options) {
options = assign({}, xmldec, doctype, options);
return new XMLBuilder(name, options).root();
};
}).call(this);
|